JAVA uses JDBC to connect to the database.
To develop a JDBC application, follow these steps:
1. Load the JDBC driver class into the Java Virtual Machine. Use the static forName (String className) method of the java. lang. Class.
Example: Class. forName ("JDBC Driver Class Name ")
2. Load the driver and establish a connection with the database. The DriverManager class follows the registered driver. When we call the getConnection () method, it traverses the driver list, wait until the driver that can connect to the database specified in the data connection string is matched. After the driver is loaded, use the getConnection method of the DriverManager class to establish a connection with the database.
Example:
Connection con = DriverManager. getConnection (database Connection string, database username, password)
3. Send the SQL statement and obtain the result set. Create an instance of the Statement interface and pass the SQL Statement to the connected database.
There are three types of Statement instances:
(1) execute static SQL statements. It is usually implemented through a Statement instance.
(2) execute dynamic SQL statements. It is usually implemented through the PreparedStatement instance.
(3) execute the database storage process. It is usually implemented through the CallableStatement instance.
Example:
Statement stmt = con.createStatement();ResultSet rs = stmt.executeQuery("select * from table1");
The Statement interface provides three methods to execute SQL statements: executeQuery, executeUpdate, and execute.
Example:
ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ; int rows = stmt.executeUpdate("INSERT INTO ...") ; boolean flag = stmt.execute(String sql) ;
4. processing result. There are two processing results:
(1) the number of records affected by this operation is returned when an update is executed.
(2) The result returned by executing the query is a ResultSet object.
Example:
while(rs.next()){ int x=rs.getInt("a"); String s=rs.getString("b"); float f=rs.getFloat("c"); }
5. Disable JDBC objects
After the operation is complete, close all the used JDBC objects to release the JDBC resources. The closing order is the opposite to the declared order.
(1) Disable record set
(2) Close the Declaration
(3) Close the connection object
If (rs! = Null) {// close record set try {rs. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (stmt! = Null) {// close the Declaration try {stmt. close () ;}catch (SQLException e) {e. printStackTrace () ;}} if (conn! = Null) {// close the connection object try {conn. close () ;}catch (SQLException e) {e. printStackTrace ();}}