使用JAVA中的JDBC在一个查询中将多行插入到两个表中

使用JAVA中的JDBC在一个查询中将多行插入到两个表中,java,mysql,sql,jdbc,Java,Mysql,Sql,Jdbc,我有两张表,学生(身份证,姓名,城市),教师(身份证,姓名,薪水)。 并且有几行需要插入Mysql数据库 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', 'Ry

我有两张表,学生(身份证,姓名,城市),教师(身份证,姓名,薪水)。 并且有几行需要插入Mysql数据库

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,我可以编写一个查询来完成它吗

使用
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...
列出学生=。。。
连接con=。。。
String insertSql=“插入学生值(?,?)”;
PreparedStatement pstmt=con.prepareStatement(插入SQL);
用于(学生:学生){
pstmt.setString(1,student.getId());//不确定是字符串还是int或long
setString(2,student.getName());
pstmt.setString(3,student.getCity());
pstmt.addBatch();
}
pstmt.executeBatch();
//关闭资源。。。
类似于您的
老师
s

更多信息:


使用
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...
列出学生=。。。
连接con=。。。
String insertSql=“插入学生值(?,?)”;
PreparedStatement pstmt=con.prepareStatement(插入SQL);
用于(学生:学生){
pstmt.setString(1,student.getId());//不确定是字符串还是int或long
setString(2,student.getName());
pstmt.setString(3,student.getCity());
pstmt.addBatch();
}
pstmt.executeBatch();
//关闭资源。。。
类似于您的
老师
s

更多信息:


我还有很多东西要学。我只是建议您可以在一个查询中插入多行,并且仍然使用占位符。嗨,Sotirios,谢谢您的评论。快速提问,“占位符”是什么?@Eric占位符是sql字符串中的
。您可以将它们与
PreparedStatement
一起使用,以设置实际要使用的值。它们在消除SQL注入等方面很有帮助。@SotiriosDelimanolis哦,很高兴知道!谢谢你分享知识,我想我知道如何学习这部分。@Eric我已经用提供有用信息的链接更新了答案,我还有很多东西要学。我只是建议您可以在一个查询中插入多行,并且仍然使用占位符。嗨,Sotirios,谢谢您的评论。快速提问,“占位符”是什么?@Eric占位符是sql字符串中的
。您可以将它们与
PreparedStatement
一起使用,以设置实际要使用的值。它们在消除SQL注入等方面很有帮助。@SotiriosDelimanolis哦,很高兴知道!谢谢分享知识,我想我知道如何学习这部分。@Eric我已经用提供有用信息的链接更新了答案