1. Basic 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
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.
A Free Trial That Lets You Build Big!
Start building with 50+ products and up to 12 months usage for Elastic Compute Service