Deep analysis of the jdbc connection database step

  • 2020-05-17 06:09:07
  • OfStack

Create a program that connects to the database with JDBC, including seven steps:
1. Load JDBC driver:
Before connecting to the database, first load the driver of the database you want to connect to to the JVM (Java virtual machine),
This is done through the static method forName(String className) of the java.lang.Class class.
Such as:
 
try{ 
// loading MySql The driving class  
Class.forName("com.mysql.jdbc.Driver") ; 
}catch(ClassNotFoundException e){ 
System.out.println(" The driver class could not be found   , the load driver failed! "); 
e.printStackTrace() ; 
} 

After a successful load, an instance of the Driver class is registered with the DriverManager class.

2. URL with JDBC connection
The & # 8226; Connecting to URL defines the protocol, subprotocol, and data source identity for connecting to a database.
The & # 8226; Written form: protocol: subprotocol: data source identification
Protocol: always start with jdbc in JDBC
Subprotocol: is the name of the driver or database management system for the bridge connection.
Data source identification: marks the address and connection port where the database source was 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.

3. Create a connection to the database
The & # 8226; To connect to the database, request and obtain the Connection object from java.sql.DriverManager,
This object represents a connection to a database.
The & # 8226; getConnectin using DriverManager (String url, String username,
The String password) method passes in the path of the database to which you want to connect, the username of the database, and
Password to get.
Such as:
 
// The connection MySql Database, username and password 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 an Statement
The & # 8226; To execute the SQL statement, you must obtain an java.sql.Statement instance, which is divided into the following 3
Type:
1. Execute the static SQL statement. This is usually done through an Statement instance.
2. Execute the dynamic SQL statement. This is usually done through an PreparedStatement instance.
3. Execute database stored procedures. This is usually done through an CallableStatement instance.
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 ways to execute SQL statements: executeQuery, executeUpdate
And execute
1. ResultSet executeQuery(String sqlString) : execute the SQL statement to query the database
, returns a result set (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
3. execute(sqlString): used to perform a combination of multiple result sets, multiple update counts, or 2
Statements.
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 performed.
2. The result returned by executing the query is an ResultSet object.
The & # 8226; ResultSet contains all the lines that meet the criteria in the SQL statement, and it provides a set of get methods for these
Access to data in a row.
The & # 8226; Get the data using the access method of the result set (ResultSet) object:
 
while(rs.next()){ 
String name = rs.getString("name") ; 
String pass = rs.getString(1) ; //  This method is efficient  
} 

(columns are numbered from left to right and start at column 1)

7. Close JDBC object
Close all JDBC objects to free JDBC resources and close the sequence harmony
In reverse order:
1. Close the record set
2. Closing statements
Close the connection object
 
if(rs != null){ //  Close recordset  
try{ 
rs.close() ; 
}catch(SQLException e){ 
e.printStackTrace() ; 
} 
} 
if(stmt != null){ //  Closing statement  
try{ 
stmt.close() ; 
}catch(SQLException e){ 
e.printStackTrace() ; 
} 
} 
if(conn != null){ //  Close the connection object  
try{ 
conn.close() ; 
}catch(SQLException e){ 
e.printStackTrace() ; 
} 
} 


Related articles: