In-depth analysis of jdbc database connection steps

Source: Internet
Author: User

Create a program to connect to the database using JDBC, which contains seven steps:
1. Load the JDBC driver:
Before connecting to the database, load the driver of the database to be connected to the JVM (Java Virtual Machine ),
This is achieved through the static method forName (String className) of the java. lang. Class.
For example: Copy codeThe Code is as follows: try {
// Load the MySql Driver Class
Class. forName ("com. mysql. jdbc. Driver ");
} Catch (ClassNotFoundException e ){
System. out. println ("The driver class cannot be found. Failed to load the driver! ");
E. printStackTrace ();
}

After the Driver class is loaded, the Driver class instance is registered to the DriverManager class.

2. Provide the URL of the JDBC connection
• The Connection URL defines the protocol, sub-protocol, and data source identification used to connect to the database.
• Writing format: Protocol: Sub-Protocol: data source ID
Protocol: always starts with JDBC in jdbc.
Sub-Protocol: the name of the Bridge Connection driver or database management system.
Data source ID: Mark the address and connection port of the database source.
Example: (MySql connection URL)
Jdbc: mysql:
// Localhost: 3306/test? UseUnicode = true & characterEncoding = gbk;
UseUnicode = true: indicates that the Unicode character set is used. If characterEncoding is set
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 must request java. SQL. DriverManager and obtain the Connection object,
This object represents a database connection.
• Use getConnectin (String url, String username,
String password ).
Password.
For example:Copy codeThe Code is as follows: // connect to the MySql database. Both the user name and password are 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 the java. SQL. Statement instance. The Statement instance is divided into three types:
Type:
1. Execute static SQL statements. It is usually implemented through a Statement instance.
2. Execute dynamic SQL statements. It is usually implemented through the PreparedStatement instance.
3. Execute the database stored procedure. It is usually implemented through the CallableStatement instance.
Specific implementation methods:Copy codeThe Code is as follows: Statement stmt = con. createStatement ();
PreparedStatement pstmt = con. prepareStatement (SQL );
CallableStatement cstmt =
Con. prepareCall ("{CALL demoSp (? ,?)} ");

5. Execute SQL statements
The Statement interface provides three methods for executing SQL statements: executeQuery and executeUpdate.
And execute
1. ResultSet executeQuery (String sqlString): run the SQL statement used to query the database.
Returns a result set 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 for executing and returning multiple result sets, multiple update counts, or a combination
Statement.
Specific implementation code:Copy codeThe Code is as follows: ResultSet rs = stmt.exe cuteQuery ("SELECT * FROM ...");
Int rows = stmt.exe cuteUpdate ("insert ...");
Boolean flag = stmt.exe cute (String SQL );

6. processing result
Two cases:
1. The number of records affected by this operation is returned when an update is executed.
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 provides
The data in the row.
• Use the access method of the result set object to obtain data:Copy codeThe Code is as follows: while (rs. next ()){
String name = rs. getString ("name ");
String pass = rs. getString (1); // This method is more efficient.
}

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

7. Disable JDBC objects
After the operation is completed, all the used JDBC objects should be closed to release the JDBC resources, close the sequence and
Reverse Order:
1. Disable record set
2. Close the statement
3. Close the connection objectCopy codeThe Code is as follows: if (rs! = Null) {// close the record set
Try {
Rs. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
If (stmt! = Null) {// close the Declaration
Try {
Stmt. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}
If (conn! = Null) {// close the connection object
Try {
Conn. close ();
} Catch (SQLException e ){
E. printStackTrace ();
}
}

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.