java complete JDBC operation database

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:  

[html] view plain copy
  1. try{      
  2. //Load the driver class of MySql      
  3. Class.forName("com.mysql.jdbc.Driver") ;      
  4. }catch(ClassNotFoundException e){      
  5. System.out.println("Could not find driver class, failed to load driver!");      
  6. e.printStackTrace ();      
  7. }  



    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:   

[html] view plain copy
  1.  //Connect to MySql database, username and password are both root      
  2.  String url = "jdbc:mysql://localhost:3306/test" ;       
  3.  String username = "root" ;      
  4.  String password = "root" ;      
  5.  try{      
  6. Connection con =       
  7.          DriverManager.getConnection(url , username , password ) ;      
  8.  }catch(SQLException se){      
  9. System.out.println("Database connection failed!");      
  10. se.printStackTrace ();      
  11.  }  


 

 

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:   

[html] view plain copy
  1. Statement stmt = con.createStatement() ;      
  2. PreparedStatement pstmt = con.prepareStatement(sql) ;      
  3. 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:

[html] view plain copy
  1. ResultSet rs = stmt.executeQuery("SELECT * FROM ...") ;      
  2. int rows = stmt.executeUpdate("INSERT INTO ...") ;      
  3. 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:   

[html] view plain copy
  1. while(rs.next()){      
  2.     String name = rs.getString("name") ;      
  3.     String  password  =  rs .getString(1) ; // This method is more efficient      
  4. }   


 
(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:

[html] view plain copy
  1. if(rs != null){ // close the recordset      
  2.    try{      
  3.          rs.close() ;      
  4.    }catch(SQLException e){      
  5.          e.printStackTrace ();      
  6.    }      
  7. }      
  8. if(stmt != null){ // close statement      
  9.    try{      
  10.       stmt.close() ;      
  11.    }catch(SQLException e){      
  12.       e.printStackTrace ();      
  13.    }      
  14. }      
  15. if(conn != null){ // close the connection object      
  16.    try{      
  17.       conn.close() ;      
  18.    }catch(SQLException e){      
  19.       e.printStackTrace ();      
  20.    }      
  21. }  


 


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324598072&siteId=291194637