Java database operation process
2. Several Common important skills:
Record Sets that can be rolled and updated
Batch update
Transaction Processing
Basic java database operation process: Get database connection-Execute SQL statements-process execution results-Release Database Connection
1. Obtain database connection
1) Use DriverManager to retrieve the database connection
Example:
String className, url, uid, pwd;
ClassName = "oracle. jdbc. driver. OracleDriver ";
Url = "jdbc: oracle: thin: @ 127.0.0.1: 1521: orasvr;
Uid = "system ";
Pwd = "manager ";
Class. forName (className );
Connection cn = DriverManager. getConnection (url, uid, pwd );
2) using jndi (java Naming and Directory Service)
Example
String jndi = "jdbc/db ";
Context ctx = (Context) new InitialContext (). lookup ("java: comp/env ");
DataSource ds = (DataSource) ctx. lookup (jndi );
Connection cn = ds. getConnection ();
Mostly used in jsp
2. Execute SQL statements
1) Use Statement to execute SQL statements
String SQL;
Statement sm = cn. createStatement ();
Sm.exe cuteQuery (SQL); // execute the data query statement (select)
Sm.exe cuteUpdate (SQL); // execute the data update statement (delete, update, insert, drop, etc.) statement. close ();
2) use PreparedStatement to execute SQL statements
String SQL;
SQL = "insert into user (id, name) values (?,?) ";
PreparedStatement ps = cn. prepareStatement (SQL );
Ps. setInt (1, xxx );
Ps. setString (2, xxx );
...
ResultSet rs = ps.exe cuteQuery (); // query
Int c = ps.exe cuteUpdate (); // update
3. Process execution results
Query statement, returns the record set ResultSet.
Update statement. A number is returned, indicating the number of records affected by the update.
ResultSet method:
1. next (): move the cursor back to a row. If the cursor is successful, true is returned. Otherwise, false is returned.
2. getInt ("id") or getSting ("name") returns the value of a field under the current cursor.
3. Release the connection.
Cn. close ();
Generally, disable ResultSet first, then close Statement (or PreparedStatement), and finally close Connection.
Record Sets that can be rolled and updated
1. Create a rolling and updated Statement