Java Database Basic Operations
1. Java database Operation Basic process
2, a few commonly used important skills:
Scrollable, updated recordsets
Batch Update
Transaction processing
Java database Operation basic process: Get database connection-Execute SQL statement-Process Execution result-release database connection
1. Get the database connection
1) using DriverManager to Access 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 services)
Example
String jndi = "jdbc/db";
Context ctx = (Context) new InitialContext().lookup("java:comp/env");
DataSource ds = (DataSource) ctx.lookup(jndi);
Connection cn = ds.getConnection();
More used in JSP
2. Execute SQL statement
1 using statement to execute SQL statements
String sql;
Statement sm = cn.createStatement();
sm.executeQuery(sql);// 执行数据查询语句(select)
sm.executeUpdate(sql);// 执行数据更新语句(delete、update、insert、drop等)statement.close();
2 using 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.executeQuery();// 查询
int c = ps.executeUpdate();// 更新
3, processing the results of implementation
Query statement that returns a recordset resultset
UPDATE statement, returning a number that represents the number of records affected by the update
The method of ResultSet
1, Next (), move the cursor back one row, or False if successful return true;
2, GETINT ("id") or getsting ("name"), returns the value of a field under the current cursor
4, Release the connection
Cn.close ();
Generally, close the resultset first, then close the statement (or PreparedStatement), and finally close the connection