Java 中使用 JDBC 执行多条 MySQL INSERT 语句的正确方式

jdbc 默认禁止执行多条 sql 语句,需在连接 url 中显式启用 `allowmultiqueries=true` 参数,方可支持分号分隔的批量 insert;但更推荐使用批处理(`addbatch()`/`executebatch

()`)以兼顾性能、安全与兼容性。

在 Java 中通过 JDBC 向 MySQL 数据库执行多条 INSERT 语句时,直接拼接分号分隔的 SQL 字符串并调用 executeUpdate() 是默认不被允许的——即使该语句能在 MySQL Workbench 中成功运行。这是因为 JDBC 驱动出于安全(防止 SQL 注入放大)和协议兼容性考虑,默认关闭了多语句执行功能。

✅ 正确启用多语句执行(不推荐用于生产环境)

若确需使用类似以下的多语句 SQL:

INSERT INTO subscriptions(...) VALUES (...);
INSERT INTO contact_informations(...) VALUES (...);

可在数据库连接 URL 中添加参数 allowMultiQueries=true:

String url = "jdbc:mysql://localhost:3306/mydb?allowMultiQueries=true&useSSL=false&serverTimezone=UTC";
Connection conn = DriverManager.getConnection(url, username, password);
Statement stmt = conn.createStatement();
int[] results = stmt.executeBatch(new String[]{
    "INSERT INTO subscriptions(user_id,`status`,subscription_type,...) VALUES (18,'ACCEPTED','FREEMIUM',...)",
    "INSERT INTO contact_informations(user_id,email,phone_number,...) VALUES (18,'test@example.com',57104998,...)"
});
// 注意:executeBatch() 返回的是各语句影响行数数组,非单个布尔值

⚠️ 重要警告

  • 启用 allowMultiQueries=true 后,PreparedStatement 将不再安全——它无法对分号后的后续语句进行参数绑定,极易引发 SQL 注入;
  • PreparedStatement 与多语句不兼容,必须改用 Statement;
  • 某些数据库连接池(如 HikariCP)可能默认禁用该选项,或需额外配置 allowMultiQueries 到 dataSourceProperties;
  • 该方式违反 JDBC 最佳实践,不建议在生产系统中使用

✅ 推荐方案:使用 PreparedStatement 批处理(安全、高效、标准)

更优解是利用 JDBC 原生批处理机制,复用同一 PreparedStatement 实例多次绑定参数并批量提交:

String sqlSub = "INSERT INTO subscriptions(user_id, `status`, subscription_type, offer_type, offer_expires, offer_effect, card_id) " +
                "VALUES (?, ?, ?, ?, ?, ?, ?)";
String sqlContact = "INSERT INTO contact_informations(user_id, email, first_digits, phone_number, phone_is_mobile, street, floor, postal, city, country_title, country_indexes) " +
                     "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

try (PreparedStatement stmtSub = conn.prepareStatement(sqlSub);
     PreparedStatement stmtContact = conn.prepareStatement(sqlContact)) {

    // 绑定并添加第一条记录到 subscriptions 批次
    stmtSub.setInt(1, 18);
    stmtSub.setString(2, "ACCEPTED");
    stmtSub.setString(3, "FREEMIUM");
    stmtSub.setNull(4, Types.VARCHAR);
    stmtSub.setNull(5, Types.TIMESTAMP);
    stmtSub.setNull(6, Types.VARCHAR);
    stmtSub.setNull(7, Types.BIGINT);
    stmtSub.addBatch();

    // 绑定并添加第一条记录到 contact_informations 批次
    stmtContact.setInt(1, 18);
    stmtContact.setString(2, "test@example.com");
    stmtContact.setInt(3, 45);
    stmtContact.setLong(4, 57104998L);
    stmtContact.setBoolean(5, false);
    stmtContact.setString(6, "Nørrevang 15");
    stmtContact.setString(7, "5. th.");
    stmtContact.setString(8, "2528");
    stmtContact.setString(9, "Holbæk");
    stmtContact.setString(10, "Tyskland");
    stmtContact.setString(11, "DE");
    stmtContact.addBatch();

    // 一次性执行两个批次(注意:各自独立提交)
    int[] subResults = stmtSub.executeBatch();   // 返回每条 INSERT 影响行数(通常为1)
    int[] contactResults = stmtContact.executeBatch();

    // 可选:验证是否全部成功
    boolean allSuccess = Arrays.stream(subResults).allMatch(r -> r == 1) &&
                         Arrays.stream(contactResults).allMatch(r -> r == 1);
}

优势总结

  • 完全保持 PreparedStatement 的预编译与参数化安全;
  • 支持事务控制(conn.setAutoCommit(false) + conn.commit());
  • 兼容所有主流 JDBC 驱动与连接池;
  • 显著提升批量插入性能(减少网络往返与解析开销);
  • 易于扩展至 N 条记录、多张表的组合插入场景。

? 总结

虽然 ?allowMultiQueries=true 能“绕过限制”执行多语句,但它牺牲了安全性与可维护性。在实际开发中,应始终优先采用 addBatch() + executeBatch() 的批处理模式,这是 JDBC 规范推荐、MySQL 官方文档认可、且被 Spring JDBC、MyBatis 等框架底层广泛采用的标准做法。