Project Summary-basic steps for JDBC database access-jdbc Data Access
Follow these steps to access the database through JDBC:
(1) load the JDBC driver of the database to classpath. during actual development of Java ee-based web applications,
Usually copy the JDBC driver of the target product to the WEB-INF/lib
(2) load the JDBC driver and register it to DriverManager.
// Oracle8/8i/9i (thin mode) Database
Class. forName ("oracle. jdbc. driver. OracleDriver"). newInstance ();
// SQL server2005 Database
Class. forName ("com. microsoft. jdbc. sqlserver. SQLServerDriver"). newInstance ();
// MySQL database
Class. forName ("com. mysql. jdbc. Driver"). newInstance ();
(3) Establish a database connection. Get Connection object
// MySQL database
String url = "jdbc: mysql: // localhost: 3306/test? User = root & passwordroot & useUniclode = true & characterEncoding = gb2312 ";
Connection conn = DriverManager. getConnection (url );
(4) create a Statement object or PreparedStatement object
Statement stat = conn. createStatement ();
// Create a PreparedStatement object
String SQL = "select * from test where userName =? And password =? ";
PreparedStatement pstmt = conn. preparedStatement (SQL );
Pstmt. setString (1, "admin ");
Pstmt. setString (2, "hephec ");
(5) Execute SQL statements
// Execute static SQL queries
String SQL = "select * from users ";
ResultSet rs1_stmt.exe cuteQuery (SQL );
// Execute dynamic SQL queries
ResultSet rs1_pstmt.exe cuteQuery ();
// Execute insert, update, delete, and other statements to define the SQL
Stmt.exe cuteUpdate (SQL );
(6) security code result record set ResultSet object
While (rs. next ()){
Out. println ("first field" + rs. getString ());
Out. println ("second field" + rs. getString ());
}
(7) disable the ResultSet, Statement, PreparedStatement, and Connection object in sequence to release the resources occupied.