JDBC Basic Notes

1. The concept of JDBC

JDBC (Java Database Connectivity) is a standard Java API for connecting java programs to databases. The basic functions of JDBC are as follows:

  • Connect to the specified database
  • Create SQL statement
  • Execute SQL (send SQL to database for processing)
  • Receive and encapsulate the processing results of the database for use by java applications

Common interfaces and classes in JDBC:

  • DriverManager : This class is used to manage database connection drivers, using the communication protocol to match connection requests from java applications with the appropriate database driver
  • Driver : This interface handles communication with the database
  • Connection : This interface has all the methods for connecting to the database. The Connection object represents the context of communication with the database. This object is used for communication between the application and the database.
  • Statement : The object created by this interface submits static SQL statements to the database, and the object created by the PreparedStatement interface processes parameterized SQL statements
  • ResultSet : This object is used to save the data retrieved from the database after the Statement is executed

Basic example of JDBC:

import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

class FirstJDBC {

    // MySQL数据库连接驱动类,数据库的URL
    static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
    static final String URL = "jdbc:mysql://localhost:3306/testjdbc";
    // 数据库用户名和密码
    static final String USER = "root";
    static final String PASSWORD = "1234";

    public static void main(String[] args){
        Connection conn = null;
        Statement stmt = null;

        try {
            // 1.注册数据库驱动
            // Class.forName(JDBC_DRIVER);

            // 使用DriverManager注册数据库驱动
            Driver mydriver = new com.mysql.jdbc.Driver();
            DriverManager.registerDriver(mydriver);

            // 2.开启一个数据库连接
            conn = DriverManager.getConnection(URL, USER, PASSWORD);

            // 3.执行查询语句,数据库返回的查询结果封装在ResultSet中
            stmt = conn.createStatement();
            String sql = "SELECT id, age, first, last FROM employees";
            ResultSet rs = stmt.executeQuery(sql);

            // 4.从结果集中提取数据
            while (rs.next()) {
                // 使用列名称获取数据(也可以使用索引获取数据)
                int id = rs.getInt("id");
                int age = rs.getInt(2);
                String first = rs.getString("first");
                String last = rs.getString(4);

                // 展示数据
                System.out.print("ID: " + id);
                System.out.print(", Age: " + age);
                System.out.print(", first: " + first);
                System.out.println(", last: " + last);
            }

            // 5.关闭各种连接,释放资源
            rs.close();
            stmt.close();
            conn.close();

        }  catch (SQLException e) {
            e.printStackTrace();
        } finally {
            // 发生异常时关闭各种资源
            try {
                if(stmt != null) {
                    stmt.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }

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

        System.out.println("Goodbye!");
    }
}

2. PrepareStatement

The PrepareStatement interface supports binding parameters to SQL statements at runtime:

// 4. 创建预处理SQL语句
String sql1 = "INSERT INTO employees VALUES (?, ?, ?)";
// 创建PrepareStatement对象
pstmt = conn.prepareStatement(sql1);
// 为预处理SQL语句中的占位符?赋值,索引为SQL中占位符出现的次序
pstmt.setInt(1, 2000);
pstmt.setInt(2, 69);
pstmt.setString(3, "Feng");
// 5. 执行SQL语句
pstmt.executeUpdate();

3. Transactions

If the JDBC connection is in autocommit mode, each SQL statement is automatically committed to the database upon completion. The setAutoCommit() method of the Connection object is used to turn off auto-commit and start a transaction. When the changes need to be committed after the changes are completed, the commit() method of the Connection object is called to commit the transaction. If the program runs abnormally, the transaction must be rolled back to cancel the update.

try {
    // 1. 注册驱动
    DriverManager.registerDriver(new com.mysql.jdbc.Driver());
    // 2. 获取Connection
    conn = DriverManager.getConnection(URL, USER, PASSWORD);
    // 3. 关闭事务自动提交
    conn.setAutoCommit(false);
    // 4. 创建并执行SQL
    String sql = "INSERT INTO employees VALUE (2001, 28, 'Hanliang', 'Zhong')";
    stmt = conn.createStatement();
    stmt.executeUpdate(sql);
    // 5. 没有异常,提交事务,更新数据库记录
    conn.commit();

    } catch (SQLException e) {
        // 6. 如果发生异常,回滚事务
        conn.rollback();
    }

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325628417&siteId=291194637