【问题标题】:Insert multiple rows into two tables in a single query using JDBC in JAVA在 JAVA 中使用 JDBC 在单个查询中将多行插入到两个表中
【发布时间】:2013-10-01 12:55:36
【问题描述】:

我有两张表学生(id,name,city),teacher(id,name,salary)。 并且有几行需要插入Mysql DB。

INSERT INTO student VALUES ('12', 'Tom', 'New York');
INSERT INTO student VALUES ('13', 'Jack', 'New York');
INSERT INTO teacher VALUES ('01', 'Joy', '42000');
INSERT INTO teacher VALUES ('02', 'Ryan', '39000');

连接器是 JAVA 中的 JDBC,我可以编写一个查询来完成它吗?

【问题讨论】:

    标签: java mysql sql jdbc


    【解决方案1】:

    使用PreparedStatement 并批量插入:

    List<Student> students = ...
    Connection con = ...
    String insertSql = "INSERT INTO student VALUES (?, ?, ?)";
    PreparedStatement pstmt = con.prepareStatement(insertSql);
    for (Student student : students) {
        pstmt.setString(1, student.getId()); //not sure if String or int or long
        pstmt.setString(2, student.getName());
        pstmt.setString(3, student.getCity());
        pstmt.addBatch();
    }
    pstmt.executeBatch();
    //close resources...
    

    与您的Teachers 类似。

    更多信息:

    【讨论】:

    • 我还有很多东西要学。我只是建议您可以在一个查询中插入多行并且仍然使用占位符。
    • 嗨 Sotirios,感谢您的评论。快速提问,什么是“占位符”?
    • @Eric 占位符是 sql 字符串中的 ?。您可以将它们与PreparedStatement 一起使用来设置您实际想要使用的值。除其他外,它们有助于消除 SQL 注入。
    • @SotiriosDelimanolis 哦,很高兴知道!感谢您分享知识,我想我知道如何学习这部分了。
    • @Eric 我已经用提供有用信息的链接更新了答案
    猜你喜欢
    • 2015-02-24
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 2016-08-04
    • 2019-04-19
    • 1970-01-01
    • 2018-05-16
    • 2011-12-03
    相关资源
    最近更新 更多