首页 > 解决方案 > 是否有多种方法可以设置 bean 值并使用 PersistentObject 将它们保存到数据库中

问题描述

我正在使用 SQL PreparedStatement 将值存储在 DB 中,使用 PersistentObject 使用布尔标志存储对象的状态,有没有办法一次存储在多个表中?

我使用了 PreparedStatement.executeUpdate()。

psmt = this.buildSQL(persistent, psmt, databaseAccess);
result=psmt.executeUpdate();
if (persistent.isNew())
    persistent.setNewFlag(false);
if (result == 0)
    return;

标签: javamysql

解决方案


很抱歉,您无法一次插入两个查询。

但是您可以使用下面发布的代码来帮助您了解更多关于在多个表中插入数据的信息。

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

推荐阅读