Six steps of JDBC

As a novice Xiaobai, I recently learned the basic knowledge of javase and mysql, but I immediately faced a new problem, how to connect java with the database. With this problem, I learned JDBC (the full name of JDBC is Java Database Connectivity) and found the answer in JDBC. JDBC connects the database and creates a program that connects the database with JDBC, There are 6 steps:

  • Load the driver (tell the Java program which brand of database to connect to)
    Before connecting to the database, first load the driver of the database you want to connect to (take MySQL as an example here) to the JVM (Java virtual machine), which can be implemented in two ways:

    1. Call the registerDriver method in DriverManage and pass in a driver implementation in the registerDriver method (not commonly used)
    For example:

DriverManager.registerDriver(new com.mysql.jdbc.Driver());

2. Through Java Implementation of static method forName(String className) of lang.class
For example:

try{//Load MySql driver class    
         Class.forName("com.mysql.jdbc.Driver") ;    
    }catch(ClassNotFoundException e){    
         System.out.println("Driver class not found, failed to load driver!");    
         e.printStackTrace() ;    
    }    

After loading successfully, an instance of the Driver class will be registered in the DriverManager class.

  • Get the connection (indicates that the channel between the JVM process and the database process is open, which belongs to the communication between processes)

    To connect to the database, you need to apply to Java sql. DriverManager obtains a Connection object, which represents the Connection of a database. Use DriverManager's getconnect (string URL, string username, string password) method to pass in the specified path, user name and password of the database to be connected.

url: uniform resource locator (absolute path of a resource in the network)
hhtps://www.baidu.com/ This is the URL.
How many parts does the URL include?

  1.	agreement
  2.	IP
  3.	PORT
  4.	Resource name

http://182.61.200.7:80/index.html

http: / / communication protocol
182.61.200.7 server IP address
Port for software on 80 server
index. The name of a resource on the HTML server

For example:

//Connect to MySql database   
     String url = "jdbc:mysql://localhost:3306/test" ;     
     String username = "root" ;    
     String password = "123456" ;    
     try{    
          Connection con = DriverManager.getConnection(url , username , password ) ;    
     }catch(SQLException se){    
          System.out.println("Database connection failed!");    
          se.printStackTrace() ;    
     }    

  • Gets the database operation object (an object that specifically executes database statements)

    To execute the SQL statement, you first need to get Java sql. Statement instance
    Execute static SQL statements. It is usually implemented through a Statement instance.

Statement stmt = conn.createStatement() ;    
  • Execute sql statement (DML.DQL...)

    1.int executeUpdate(String sqlString): used to execute DML statements (insert,delete, update). The return value is the number of records affecting the database;

//4. Execute SQL statement
     String sql = "delete from dept where deptno = 50";
     int count = stmt.executeUpdate(sql);
     System.out.println(count == 1 ? "Delete succeeded" : "Deletion failed");

2.ResultSet executeQuery(String sqlString): used to execute DQL statements and return a ResultSet object

//4. Execute SQL statement
	String sql = "select empno,ename,sal from emp";
	rs = stmt.excuteQuery(sql);
  • Process the query result set (step 5 will be executed only when the select statement is executed in step 4)

    Call the next method in the ResultSet (a bit like an iterator in a collection, but not the same as a collection)
    • the ResultSet contains all rows that meet the conditions in the SQL statement, and it provides access to the data in these rows through a set of get methods.
    • obtain data using the access method of the ResultSet object:

	while(rs.next()){    
         String name = rs.getString("name") ; //This way is more robust   
         String name= rs.getString(1);  
         System.out.println(name);
     }    

The feature of getString() method is that no matter what the data type in the database is, it is retrieved in the form of String.
Columns are numbered from left to right and start with column 1
(all subscripts in JDBC start from 1, not 0)

  • Release resources (be sure to close resources in time after using them)

    After the operation is completed, close all used JDBC objects to release JDBC resources.
    1. Close requestSet first
    2. Then close preparedStatement
    3. Finally, close the connection object connection

Close from small to large

if(rs !=null){   // Close Recordset    
   try {
      rs.close();
   } catch (SQLException e) {
      e.printStackTrace();
   }
}    
  if(stmt !=null){   // Close declaration    
   try {
      stmt.close();
   } catch (SQLException e) {
      e.printStackTrace();
   }
}
if(conn !=null){  // Close connection object    
   try {
      conn.close();
   } catch (SQLException e) {
      e.printStackTrace();
   }
}

ok, the above are the six steps of JDBC. If there is any error, please correct it civilly.

Keywords: Java Eclipse

Added by r3dk1t on Wed, 19 Jan 2022 04:57:22 +0200