我正在使用SQL PreparedStatement使用PersistentObject将数据存储在DB中,并使用布尔标志存储对象的状态,有没有办法一次存储在多个表中?
我使用了PreparedStatement.executeUpdate()。
psmt = this.buildSQL(persistent, psmt, databaseAccess);
result=psmt.executeUpdate();
if (persistent.isNew())
persistent.setNewFlag(false);
if (result == 0)
return;
答案 0 :(得分:1)
很抱歉您无法一次插入两个查询。
但是您可以使用下面发布的代码,这可以帮助您了解有关在多个表中插入数据的更多信息。
try (Connection connection = **strong text**DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb", "root", "password")) {
try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO PUBLISHER (CODE, PUBLISHER_NAME) VALUES (?, ?)")) {
stmt.setString(1, book.getPublisher().getCode());
stmt.setString(2, book.getPublisher().getName());
stmt.executeUpdate();
}
// stmt is auto closed here, even if SQLException is thrown
try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO BOOK (ISBN, BOOK_NAME, PUBLISHER_CODE) VALUES (?, ?, ?)");
stmt.setString(1, book.getIsbn());
stmt.setString(2, book.getName());
stmt.setString(3, book.getPublisher().getCode());
stmt.executeUpdate();
}
// stmt is auto closed here, even if SQLException is thrown
}// connection is auto closed here, even if SQLException is thrown