First, you need to import the JDBC jar package;
Next, the code:
Class.forName(xxx.xx.xx) returns a class
The function of Class.forName(xxx.xx.xx) is to require the JVM to find and load the specified class, that is, the JVM will execute the static code segment of the class.
JDBC connection database
• 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 java.lang.Class class.
For example:
try{ //Load MySql's driver class Class.forName("com.mysql.jdbc.Driver"); //Description: About the forName method of the Class class//Load the class in className into memory space through this method/* The forName method of the Class class, as follows: @CallerSensitive public static Class<?> forName(String className) throws ClassNotFoundException { Class<?> caller = Reflection.getCallerClass();//Get the object that calls this method, for example, the incom.mysql.jdbc.Driver" is passed, jvm will go to the com.mysql.jdbc of the driver jar package, and use the caller's class loader to call the Driver class (the Driver class in com.mysql.jdbc inherits from the Driver interface in the java.sql package, the header of the class: public class com.mysql.jdbc.Driver extends com.mysql.jdbc.NonRegisteringDriver implements java.sql.Driver {} It can be seen that this class inherits the java.sql.Driver interface, so it can be called using a combination of factory mode and singleton mode in the program) return forName0(className, true, ClassLoader.getClassLoader(caller), caller);//If an exception occurs in loading, it returns an exception //forName0(className, true, ClassLoader.getClassLoader(caller), caller); // ClassLoader.getClassLoader(caller) Use the class loader of the class that calls this method to call the class corresponding to the driver interface} */}catch(ClassNotFoundException e){ System.out.println("The driver class cannot be found, the driver loading failed!"); e.printStackTrace() ;}After successful loading, an instance of the Driver class will be registered in the DriverManager class. DriverManager.getConnection(url , username , password ) operation, will be discussed later
2. Provide the URL for JDBC connection
The connection URL defines the protocol, sub-protocol, and data source identifier when connecting to the database.
Writing format: 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
The full path is jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=gbk;
useUnicode=true: indicates whether to use 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 it from java.sql.DriverManager and get the Connection object.
This object represents a connection to a database.
• Use DriverManager's getConnectin(String url, String username,
The String password ) method passes the specified path, database username and password of the database to be connected to to obtain.
For example:
//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 = 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 a java.sql.Statement instance. Statement instances are divided into the following 3 types:
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:
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 to execute SQL statements: executeQuery, executeUpdate and execute
1. ResultSet executeQuery(String sqlString): Execute SQL statements to query the database and 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 statements that return multiple result sets, multiple update counts, or a combination of both.
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 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 access to the data in these rows through a set of get methods.
• Use the access method of the result set (ResultSet) object to get 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. Close JDBC object
After the operation is completed, all the used JDBC objects must be closed to release JDBC resources. The order of closing and declarations are reversed:
1. Close the record set
2. Close statement
3. Close the connection object
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() ; } }The above is a detailed explanation of the JDBC database connection process, driver loading and design pattern introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!