JDBC loading process and JDBC Loading Process
The process of jdbc loading.
For the bridge mode, refer to: Design Mode: Bridge Mode
Blog purpose: Use graphs to speak
JDBC procedure
Connect to the database through JDBC
• Create a program to connect to the database using JDBC, which consists of 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:
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: In JDBC, the sub-Protocol always starts with jdbc: the driver of the bridge connection or the name of the database management system.
Data source ID: Mark the address and connection port of the database source.
For 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 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 java. SQL. DriverManager and obtain the Connection object, which represents the Connection of a database.
• Use the getConnectin (String url, String username, String password) method of DriverManager to pass in the path of the database to be connected, and obtain the username and password of the database.
For example: // connect to the MySql database. The username and password are both root.
String url = "jdbc: mysql: // localhost: 3306/test ";
String username = "root ";
String password = "root ";
Try {
Connection con = DriverManager. getConnection (url, username, password );
} Catch (SQLException ...... remaining full text>
How to load JDBC driver in Java
String url = "jdbc: mysql: // localhost: 3306/test ";
String user = "root ";
String pwd = "root ";
Class. forName ("com. mysql. jdbc. Driver"); // The load Driver is a Class in your jar package.
Connection conn = DriverManager. getConnection (url, user, pwd)