首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 綜合教學

JDBC 入門:Statement 實現數據插入完整示例與資源管理規範

     編輯:Java 綜合教學

JDBC 入門:Statement 實現數據插入完整示例與資源管理規範

JDBC (Java Database Connectivity) 是 Java 操作關係數據庫的基礎 API。本文以 MySQL 為例,演示使用 `Statement` 執行 INSERT 語句的標準流程,重點講解資源獲取、執行、關閉的正確姿勢。

核心步驟

  1. 加載驅動:`Class.forName("com.mysql.jdbc.Driver")`
  2. 建立連接:`DriverManager.getConnection(url, user, pwd)`
  3. 創建 Statement:`conn.createStatement()`
  4. 執行 SQL:`stmt.executeUpdate(sql)`(INSERT/UPDATE/DELETE)
  5. 釋放資源:先關 Statement,後關 Connection,放在 `finally` 塊中

完整代碼

import java.sql.*;
import java.io.InputStream;
import java.util.Properties;

public class JdbcInsertDemo {

    public static void main(String[] args) {
        Connection conn = null;
        Statement stmt = null;
        try {
            // 1. 讀取配置文件
            Properties props = loadProps("jdbc.properties");
            String driver = props.getProperty("driver");
            String url = props.getProperty("jdbcUrl");
            String user = props.getProperty("user");
            String pwd = props.getProperty("password");

            // 2. 加載驅動
            Class.forName(driver);

            // 3. 獲取連接
            conn = DriverManager.getConnection(url, user, pwd);

            // 4. 創建 Statement
            stmt = conn.createStatement();

            // 5. 準備 SQL
            String sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) " +
                         "VALUES ('李小龍', 'long@live.com', '1940-11-27')";

            // 6. 執行插入
            int affected = stmt.executeUpdate(sql);
            System.out.println("受影響行數: " + affected + (affected > 0 ? " 插入成功" : " 插入失敗"));

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 7. 關閉資源(逆序)
            closeQuietly(stmt);
            closeQuietly(conn);
        }
    }

    private static Properties loadProps(String fileName) throws Exception {
        try (InputStream is = JdbcInsertDemo.class.getClassLoader().getResourceAsStream(fileName)) {
            Properties p = new Properties();
            p.load(is);
            return p;
        }
    }

    private static void closeQuietly(AutoCloseable c) {
        if (c != null) try { c.close(); } catch (Exception ignored) {}
    }
}

配置文件 jdbc.properties

driver=com.mysql.jdbc.Driver
jdbcUrl=jdbc:mysql://localhost:3306/testdb?useSSL=false&serverTimezone=UTC
user=root
password=root

數據庫表結構

CREATE TABLE customers (
    id INT PRIMARY KEY AUTO_INCREMENT,
    NAME VARCHAR(50),
    EMAIL VARCHAR(100),
    BIRTH DATE
);

關鍵點解析

1. Statement vs PreparedStatement

特性StatementPreparedStatement
SQL 注入防護無,需手動轉義參數佔位符 `?` 自動防注入
性能每次編譯預編譯,批量執行極快
適用場景簡單、無參數、極少執行所有生產環境業務 SQL

生產代碼請務必使用 PreparedStatement!

2. 資源關閉順序與異常安全

// 錯誤示範:若 stmt.close() 拋異常,conn 永不關閉
stmt.close();
conn.close();

// 正確模式:分別 try-catch 或使用 try-with-resources (Java 7+)
try (Connection conn = DriverManager.getConnection(...);
     PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, "value");
    ps.executeUpdate();
} // 自動關閉,即使拋異常也安全

3. 配置文件隔離

將數據庫連接信息外部化到 `.properties` 文件,便於多環境(開發/測試/生產)切換,避免硬編碼洩露密碼。

進階:PreparedStatement 參數化插入

String sql = "INSERT INTO customers (NAME, EMAIL, BIRTH) VALUES (?, ?, ?)";
try (Connection conn = getConnection();
     PreparedStatement ps = conn.prepareStatement(sql)) {
    ps.setString(1, "Bruce Lee");
    ps.setString(2, "bruce@lee.com");
    ps.setDate(3, Date.valueOf("1940-11-27"));
    ps.executeUpdate();
}

總結

JDBC 基礎雖簡單,但資源管理、SQL 注入防護、連接池複用等工程化細節決定系統穩定性。初學者應從 `PreparedStatement` + `try-with-resources` 起步,養成良好習慣。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved