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), which is implemented 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"); }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.
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:
Indicates the use of Unicode character sets.
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 the java.sql.DriverManager and obtain the Connection object, which represents the connection to a database.
• Use DriverManager to getConnectin(String url, String username, String password)
Methods are obtained by passing the specified path, database username and password to the database to be connected.
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
package me.clfeng.jdbc;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;public class DBHelper { public static final String url = "jdbc:mysql://localhost:3306/mybatis"; public static final String name = "com.mysql.jdbc.Driver"; public static final String username = "root"; public static final String password = "123456"; public Connection conn = null; public PreparedStatement statement = null; public DBHelper(String sql) { try { Class.forName(name);// Specify the connection type conn = DriverManager.getConnection(url, username, password);// Get the connection statement = conn.prepareStatement(sql);// Prepare the execution statement} catch (Exception e) { e.printStackTrace(); } } // Release the resource public void close() { try { this.conn.close(); this.statement.close(); } catch (Exception e) { e.printStackTrace(); } }} Test code:
package me.clfeng.jdbc;import java.sql.ResultSet;public class JdbcTest { static String sql = null; static DBHelper dbHelper = null; static ResultSet resultSet = null; public static void main(String[] args) { sql = "select * from user"; dbHelper = new DBHelper(sql); try { resultSet = dbHelper.statement.executeQuery();// Execute the statement to get the result set while (resultSet.next()) { int id = resultSet.getInt(1); String name = resultSet.getString(2); int age = resultSet.getInt(3); System.out .println("id=" + id + ",name=" + name + ",age=" + age); } resultSet.close(); dbHelper.close(); } catch (Exception e) { e.printStackTrace(); } }}The above steps and simple implementation code of Jdbc are all the content I share with you. I hope you can give you a reference and I hope you can support Wulin.com more.