簡體   English   中英

在JAVA中使用JDBC在單個查詢中將多行插入到兩個表中

[英]Insert multiple rows into two tables in a single query using JDBC in JAVA

我有兩張桌子學生(身份證,姓名,城市),老師(身份證,姓名,工資)。 插入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,我可以編寫一個查詢來做到這一點。

使用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...

與您的Teacher相似。

更多信息:

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM