When we are learning the interface. You can make some method calls in it. However, the JDBC we are going to talk about today is also an interface for connecting to the database, but it is very different from the class interface, so everyone should pay attention to the distinction. Below we have sorted out the steps to build JDBC. For those who are not familiar with such operations, let’s take a look at the specific content.
1. Load the database driver. Usually the forName() static method of the Class class is used to load the driver. For example, the following code:
//Load driver Class.forName(driverClass)
2. Obtain the database connection through DriverManager. DriverManager provides the following methods:
// Get the database connection DriverManager.getConnection(String url,String user,String password);
3. Create a Statement object through the Connection object. There are three methods for creating Statement in Connection:
createStatement(): Create a basic Statement object.
prepareStatement(String sql): Creates a precompiled Statement object based on the incoming SQL statement.
prepareCall(String sql): Creates a CallableStatement object based on the incoming SQL statement.
4. Use Statement to execute SQL statements. All Statements have the following three methods to execute SQL statements:
execute(): can execute any SQL statement, but it is more troublesome.
executeUpdate(): Mainly used to execute DML and DDL statements. Executing a DML statement returns the number of rows affected by the SQL statement, and executing a DDL statement returns 0.
executeQuery(): can only execute query statements, and after execution returns a ResultSet object representing the query results.
5. Operation result set. If the executed SQL statement is a query statement, the execution result will return a ResultSet object, which stores the results of the SQL statement query. Query results can be obtained by operating this object.
6. Recycle database resources, including closing ResultSet, Statement, Connection and other resources.
The above is the operation of building JDBC applications in Java. After watching this film's introduction to building JDBC, you can follow the specific steps to practice. More Java learning guide: java tutorial