Java uses JDBC to operate the database includes the following 7 main steps:
1. Load the JDBC driver
Before connecting to the database, first load the driver of the database you want to connect to the JVM (Java Virtual Machine), which is implemented by the static method forName(String className) of the java.lang.Class class. E.g:
- try{
- //Load the driver class of MySql
- Class.forName("com.mysql.jdbc.Driver") ;
- }catch(ClassNotFoundException e){
- System.out.println("Could not find driver class, failed to load driver!");
- e.printStackTrace ();
- }
After successful loading, an instance of the Driver class is registered into the DriverManager class.
2. Provide the URL of the JDBC connection
The connection URL defines the protocol, sub-protocol, and data source identifier when connecting to the database.
Writing form: Protocol: Subprotocol: Data Source Identification
Protocol: Always start with jdbc in JDBC Subprotocol
: is the name of the bridge connection driver or database management system.
Data source identification: mark the address and connection port where the database source is found.
For example: (MySql connection URL) jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true: indicates the use of the Unicode character set. If characterEncoding is set to gb2312 or GBK, this parameter must be set to true. characterEncoding=gbk: Character encoding method.
3. Create a connection to the database
To connect to the database, you need to request from java.sql.DriverManager and get the Connection object, which represents a database connection. Use the getConnectin(String url, String username, String password) method of DriverManager to pass in the specified path to the database to be connected to , database username and password to obtain.
E.g:
- //Connect to MySql database, username and password are both root
- String url = "jdbc:mysql://localhost:3306/test" ;
- String username = "root" ;
- String password = "root" ;
- try{
- Connection con =
- DriverManager.getConnection(url , username , password ) ;
- }catch(SQLException se){
- System.out.println("Database connection failed!");
- se.printStackTrace ();
- }
4. Create a Statement
To execute an SQL statement, you must obtain an instance of java.sql.Statement. The Statement instance is divided into the following three types:
1. Execute a static SQL statement. Usually implemented through a Statement instance.
2. Execute dynamic SQL statements. Usually implemented through a PreparedStatement instance.
3. Execute the database stored procedure. Usually implemented through a CallableStatement instance.
The specific implementation method:
- Statement stmt = con.createStatement() ;
- PreparedStatement pstmt = con.prepareStatement(sql) ;
- CallableStatement cstmt = con.prepareCall("{CALL demoSp(? , ?)}") ;
5. Execute the SQL statement
The Statement interface provides three methods for executing SQL statements: executeQuery, executeUpdate and execute
1. ResultSet executeQuery(String sqlString): executes the SQL statement that queries the database and returns a ResultSet object.
2. int executeUpdate(String sqlString): used to execute INSERT, UPDATE or DELETE statements and SQL DDL statements, such as: CREATE TABLE and DROP TABLE, etc.
3. execute(sqlString): used to execute multiple result sets, multiple updates A statement that counts or a combination of the two.
The specific implementation code:
- ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;
- int rows = stmt.executeUpdate("INSERT INTO ...") ;
- boolean flag = stmt.execute(String sql) ;
6. Processing results
Two cases:
1. The number of records affected by this operation is returned when the update is executed.
2. The result returned by executing the query is a ResultSet object.
A ResultSet contains all the rows that meet the conditions in the SQL statement, and it provides access to the data in those rows through a set of get methods. Use the access methods of the ResultSet object to get the data, for example:
- while(rs.next()){
- String name = rs.getString("name") ;
- String password = rs .getString(1) ; // This method is more efficient
- }
(columns are numbered from left to right and start at column 1)
7. Close the JDBC object
After the operation is completed, all used JDBC objects should be closed to release JDBC resources. The closing order is opposite to that of the declaration:
1. Close the recordset
2. Close the statement
3. Close the connection object
. For example:
- if(rs != null){ // close the recordset
- try{
- rs.close() ;
- }catch(SQLException e){
- e.printStackTrace ();
- }
- }
- if(stmt != null){ // close statement
- try{
- stmt.close() ;
- }catch(SQLException e){
- e.printStackTrace ();
- }
- }
- if(conn != null){ // close the connection object
- try{
- conn.close() ;
- }catch(SQLException e){
- e.printStackTrace ();
- }
- }