加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

java – PreparedStatement:如何使用JDBC将数据插入到多个表中

发布时间:2020-12-15 00:01:28 所属栏目:Java 来源:网络整理
导读:有人能告诉我是否第一个stmt.close();以下JDBC代码中是否需要针对两个不同的表执行两个不同的SQL查询? public class MyService { private Connection connection = null; public void save(Book book) { try { Class.forName("com.mysql.jdbc.Driver"); con
有人能告诉我是否第一个stmt.close();以下JDBC代码中是否需要针对两个不同的表执行两个不同的SQL查询?
public class MyService {
    private Connection connection = null;

    public void save(Book book) {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","root","password"); 

            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.close(); //1

            stmt = connection.prepareStatement("INSERT INTO BOOK (ISBN,BOOK_NAME,PUBLISHER_CODE) VALUES (?,?,book.getIsbn());  
            stmt.setString(2,book.getName());
            stmt.setString(3,book.getPublisher().getCode());
            stmt.executeUpdate();

            stmt.close(); //2       
        } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } 
        finally { connection.close(); }         
    }
}

解决方法

在我的书中,我总是建议关闭已经打开的资源以避免可能的泄漏.

稍微更现代的方式是使用try-with-resources:

try (Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydb","password")) {

    try (PreparedStatement stmt = connection.prepareStatement("INSERT INTO PUBLISHER (CODE,?)")) {
        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,?)");
        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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读