1. Process:
1>Register driver class: Class.forName()
2>Connect to the database:
Copy the code code as follows:
String url = "jdbc:sqlserver://localhost:1433;DatabaseName=DataBaseName";
String uername = "dbuser";
String password = "secret";
Connection conn = DriverManager.getConnection(url,username,password);
3>Execute sql statement:
Statement stat = conn.createStatement();
String command = "UPDATE BOOKS";
stat.executeUpdate(command);
[/code]
2.java.sql.Statement() (three execution methods)
The first type: execute();void can execute any sql statement
The second type: executeUpdate();int
Can be executed: INSERT UPDATE DELETE
CREATE TABLE;DROP TABLE
Returns: number of rows affected
The third type: executeQuery();ResultSet
Execution: SELECT
Returns: a ResultSet object, iterated one row at a time
example:
Copy the code code as follows:
ResultSet rs = stat.executeQuery("SELECT * FORM BOOKS");
while(rs.next()){
look at a row of the result set
}
rs.getString(1); returns the value of the first column of the current row
rs.getDouble("Price");
getResultSet();ResultSet
Returns the result set; if empty, null
getUpdateCount();int returns the number of affected rows, if not updated, returns -1
close();void closes the Statement object and its corresponding result set
isClose();boolean true if the statement is closed
3.java.sql.ResultSet (result set operation method)
next();boolean moves forward one line to the last line, returns false
getXxx(int columnNum);Xxx
getXxx(String columnNum);XxxXxx refers to int double String Date
findColumn(String columnName);int gives the column name and returns the column number
close();void closes the current result set
isClose();boolean true if the statement is closed
4. Principles:
1>Each Connection object can create one or more Statement objects
The same Statement object can be used for multiple unrelated commands and queries, but only one result set can be opened.
2>The close method should be called immediately after use
3>If the Statement object has an open result set, the result set will be automatically closed after calling close();
If the Connection class closes all statements on the connection