SoFunction
Updated on 2025-03-08

In-depth analysis of the steps for connecting to the database by jdbc

Create a program that connects to the database with JDBC, which contains 7 steps:
1. Load the JDBC driver
Before connecting to the database, you must first load the driver of the database you want to connect to to the JVM (Java virtual machine).
This is achieved through the static method forName(String className) of the class.
For example:
Copy the codeThe code is as follows:

try{
//Load MySql driver class
("") ;
}catch(ClassNotFoundException e){
("Driver class not found, driver loading failed!");
() ;
}

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

2. Provide the URL for JDBC connection
•The connection URL defines the protocol, subprotocol, and data source identifier when connecting to the database.
•Writing form: protocol: sub-protocol: data source identification
Protocol: In JDBC, always start with jdbc
Subprotocol: is the bridge-connected driver or database management system name.
Data source identification: Tag the address and connection port where the database source is found.
For example: (MySql's connection URL)
jdbc:mysql:
//localhost:3306/test?useUnicode=true&characterEncoding=gbk ;
useUnicode=true: means using 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 database connection
•To connect to the database, you need to request and obtain the Connection object.
This object represents a connection to a database.
• Use DriverManager's getConnectin(String url, String username,
The String password ) method passes into the specified database path, database username and
Password to get.
For example:
Copy the codeThe code is as follows:

//Connect the MySql database, the username and password are root
String url = "jdbc:mysql://localhost:3306/test" ;
String username = "root" ;
String password = "root" ;
try{
Connection con =
(url , username , password ) ;
}catch(SQLException se){
("Database connection failed!");
() ;
}


4. Create a Statement
•To execute SQL statements, an instance must be obtained. Statement instances are divided into the following 3
Type:
1. Execute static SQL statements. Usually implemented through Statement instances.
2. Execute dynamic SQL statements. Usually implemented through PreparedStatement instance.
3. Execute the database stored procedure. Usually implemented through CallableStatement instance.
Specific implementation methods:
Copy the codeThe code is as follows:

Statement stmt = () ;
PreparedStatement pstmt = (sql) ;
CallableStatement cstmt =
("{CALL demoSp(? , ?)}") ;


5. Execute SQL statements
The Statement interface provides three methods to execute SQL statements: executeQuery and executeUpdate
and execute
1. ResultSet executeQuery(String sqlString): execute SQL statements for querying database
, return 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, etc.
3. execute(sqlString): used to execute return multiple result sets, multiple update counts, or a combination of both.
Statement.
Specific implementation code:
Copy the codeThe code is as follows:

ResultSet rs = ("SELECT * FROM ...") ;
int rows = ("INSERT INTO ...") ;
boolean flag = (String sql) ;


6. Processing results
Two situations:
1. Execution of update returns the number of records affected by this operation.
2. The result returned by executing the query is a ResultSet object.
• The ResultSet contains all rows that meet the conditions in the SQL statement, and it provides these through a set of get methods.
Access to data in rows.
• Use the access method of the result set (ResultSet) object to get data:
Copy the codeThe code is as follows:

while(()){
String name = ("name") ;
String pass = (1); // This method is more efficient
}

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

7. Close JDBC object
After the operation is completed, all JDBC objects used must be closed to release JDBC resources, and the closing order and harmony are
The order is opposite:
1. Close the record set
2. Close statement
3. Close the connection object
Copy the codeThe code is as follows:

if(rs != null){ // Close the record set
try{
() ;
}catch(SQLException e){
() ;
}
}
if(stmt != null){ // Close the declaration
try{
() ;
}catch(SQLException e){
() ;
}
}
if(conn != null){ // Close the connection object
try{
() ;
}catch(SQLException e){
() ;
}
}