Detailed explanation of jdbc database connection process and driver loading and design mode, and jdbc Design Mode
First, import the JDBC jar package;
Next, the Code is as follows:
Class. forName (xxx. xx. xx) returns a Class. forName (xxx. xx. xx) is used to require the JVM to find and load the specified class, that is, the JVM will execute the static code segment of the class.
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. forName ("com. mysql. jdbc. driver "); // Description: forName method of the Class // use this method to load the Class in className to the memory space. The forName method of the * Class is as follows: @ CallerSensitive public static Class <?> ForName (String className) throws ClassNotFoundException {Class <?> Caller = Reflection. getCallerClass (); // obtain the object that calls this method. For example, the object that is passed in is "com. mysql. jdbc. driver ", jvm will go to the com. mysql. in jdbc, the caller's class loader is used to call the Driver class (com. mysql. the Driver class in jdbc inherits from java. the Driver interface in the SQL package. the header of this class is public class com. mysql. jdbc. driver extends com. mysql. jdbc. nonRegisteringDriver implements java. SQL. driver {} shows that this class inherits java. SQL. driver Interface, so you can use the factory mode and Singleton mode in the program to call) return forName0 (className, true, ClassLoader. getCl AssLoader (caller), caller); // if an exception occurs during loading, the system returns an exception // forName0 (className, true, ClassLoader. getClassLoader (caller), caller); // ClassLoader. getClassLoader (caller) uses the class loader that calls this method to call the class} */} 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. DriverManager. getConnection (url, username, password) operation.
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
Full path: jdbc: mysql: // localhost: 3306/test? UseUnicode = true & characterEncoding = gbk;
UseUnicode =True: Indicates whether to use the Unicode Character Set. If characterEncoding is set to gb2312 or GBK, this parameter must be setTrue.
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.
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 se) {System. out. println ("database connection failed! "); Se. printStackTrace ();}
4. Create a Statement
• To execute SQL statements, you must obtain the java. SQL. Statement instance. The Statement instance can be divided into the following types:
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:
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, executeUpdate, and execute.
1. ResultSet executeQuery (String sqlString): executes the SQL statement used to query the database and returns a result set object.
2,IntExecuteUpdate (String sqlString): used to execute INSERT, UPDATE, or DELETE statements and SQL DDL statements, such as CREATE TABLE and DROP TABLE.
3. execute (sqlString): it is used to execute statements that return multiple result sets, multiple update counts, or a combination of the two.
Specific implementation code:
ResultSet rs = stmt.exe cuteQuery ("SELECT * FROM ...");
IntRows = stmt.exe cuteUpdate ("insert ...");
BooleanFlag = 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.
• 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.
• Use the access method of the result set object to obtain data:
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 complete, you need to close all the used JDBC objects to release the JDBC resources. The order of closure is the opposite of the declared order:
1. Disable record set
2. Close the statement
3. Close the connection object
If (rs! = Null) {// close 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 ();}}