[Java] Detailed explanation of the use of JDBC

Overview of JDBC

The full name of JDBC is Java Database Connectivity (Java Database Connectivity), which is a set of Java API for executing SQL statements. Applications can connect to relational databases through this set of APIs, and use SQL statements to complete operations such as querying, adding, updating, and deleting data in the database. To put it bluntly, it is to use the Java language to operate the database. It turns out that we operate the database by using SQL statements on the console to operate the database, and JDBC uses the Java language to send SQL statements to the database.

Java uses JDBC detailed steps

Create a maven project in IDEA, and then import mysqlthe jar package

 <dependency>
   <groupId>mysql</groupId>
   <artifactId>mysql-connector-java</artifactId>
   <version>8.0.20</version>
 </dependency>

1. Load the database driver

 // 1.加载驱动程序
 Class.forName("com.mysql.cj.jdbc.Driver");

If it is a version below mysql 8.0

Class.forName("com.mysql.jdbc.Driver");

2. Obtain the database link

  // 2.获得数据库链接
String URL = "jdbc:mysql://localhost:3306/springtest?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
String USER = "root";
String PASSWORD = "123456";
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);

ConnectionObject Common Methods

method describe
prepareStatement(sql) Create a PrepareSatement object that sends precompiled sql to the database.
prepareCall(sql) Create a callableStatement object that executes the stored procedure.
createStatement() Create a statement object that sends sql to the database.
setAutoCommit(boolean autoCommit) Sets whether transactions are automatically committed.
commit() Commit a transaction on the link.
rollback() Roll back the transaction on this link.

3. Execute the SQL statement

Method 1: Statement

String sql="select * from user where name='"+name+"'";
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery(sql);

Common methods of the Statement object:

method describe
executeQuery(String sql) Used to send query statements to data
executeUpdate(String sql) Used to send insert, update or delete statements to the database
execute(String sql) Used to send arbitrary sql statements to the database
addBatch(String sql) Put multiple sql statements into a batch.
executeBatch() Send a batch of sql statements to the database for execution.

Method 2: PreperedStatement

PreperedStatementyes Statementsubclass

String sql="select * from user where name=?";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, name);
ResultSet rs = statement.executeQuery();

Statementand PreperedStatementcontrast

  • PreperedStatement can avoid the problem of SQL injection
  • Statement will cause the database to compile SQL frequently, which may cause database buffer overflow. PreparedStatement can precompile SQL to improve the execution efficiency of the database.
  • For parameters in SQL, PreperedStatement allows the use of placeholders for replacement, simplifying the writing of SQL statements.

4. Get the result

  while (rs.next()) {
    
    
       System.out.println(rs.getString("name") + " " + rs.getString("age"));
   }

ResultSetCommon method:
get row

  • next(): move to the next line
  • Previous(): Move to the previous line
  • absolute(int row): move to the specified row
  • beforeFirst(): Move the front of the resultSet.
  • afterLast() : Move to the end of the resultSet.

5. Release resources

if (rs != null) {
    
    
   try {
    
    
         rs.close();
     } catch (Exception e) {
    
    
         e.printStackTrace();
     }
     rs = null;

 }
 if (statement != null) {
    
    
     try {
    
    
         statement.close();
     } catch (Exception e) {
    
    
         e.printStackTrace();
     }

 }
 if (conn != null) {
    
    
     try {
    
    
         conn.close();
     } catch (Exception e) {
    
    
         e.printStackTrace();
     }

 }

full code

import java.sql.*;


public class App {
    
    
    public static void main(String[] args) {
    
    
        Connection conn = null;
//        Statement statement = null;
        PreparedStatement statement = null;
        ResultSet rs = null;

        try {
    
    
            // 1.加载驱动程序
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2.获得数据库链接
            String URL = "jdbc:mysql://localhost:3306/springtest?characterEncoding=utf-8&serverTimezone=UTC&useSSL=false";
            String USER = "root";
            String PASSWORD = "123456";
            conn = DriverManager.getConnection(URL, USER, PASSWORD);
            // 3.通过数据库的连接操作数据库,实现增删改查(使用Statement类)
            String name = "张三1";
            //预编译
            String sql = "select * from user where name=?";
            statement = conn.prepareStatement(sql);
            statement.setString(1, name);
            rs = statement.executeQuery();
/*			String sql="select * from user where name='"+name+"'";
			Statement statement = conn.createStatement();
			ResultSet rs = statement.executeQuery(sql);*/
            // 4.处理数据库的返回结果(使用ResultSet类)
            while (rs.next()) {
    
    
                System.out.println(rs.getString("name") + " " + rs.getString("age"));
            }

        } catch (ClassNotFoundException e) {
    
    
            e.printStackTrace();
        } catch (SQLException e) {
    
    
            e.printStackTrace();
        } finally {
    
    
            //6.关闭链接,释放资源
            if (rs != null) {
    
    
                try {
    
    
                    rs.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }
                rs = null;

            }
            if (statement != null) {
    
    
                try {
    
    
                    statement.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }

            }
            if (conn != null) {
    
    
                try {
    
    
                    conn.close();
                } catch (Exception e) {
    
    
                    e.printStackTrace();
                }

            }
        }
    }
 

}

Guess you like

Origin blog.csdn.net/huweiliyi/article/details/107872287