java—一个数据库连接,多线程插入,使用事务同时更新数据

neekobn8  于 2021-07-13  发布在  Java
关注(0)|答案(0)|浏览(295)

我有点困惑,我知道事务隔离。
假设我有3个线程同时使用一个数据库连接,它们使用事务来插入和更新这样的数据。

new Thread(new Runnable() {
            Connection connection1 = null;
            @Override
            public void run() {
                try {
                    connection1 = MysqlConnectionManager.getConnection();
                    connection1.setAutoCommit(false);
                    //execute some insert or update queries
                    connection1.commit();
                } catch (Exception e) {
                    e.printStackTrace();
                }finally {
                    if(connection1 != null)
                        try {
                            connection1.setAutoCommit(true);
                        } catch (SQLException e) {
                            e.printStackTrace();
                        }
                }
            }
        }).start();

假设其中一个线程有一个查询错误。这意味着 connection1.commit(); 不会执行和调用 connection1.setAutoCommit(true); 而其他线程尚未调用commit。其他线程是否会自动提交执行的查询(即使有错误或错误) connection1.setAutoCommit(true); 不会影响其他线程中的连接吗?别忘了我只使用了一个连接。
我该怎么做才能在没有任何问题的情况下使用这些线程?
我在考虑在每个线程中创建一个新的连接,但是,我害怕mysql数据库对多个连接的抱怨。

暂无答案!

目前还没有任何答案,快来回答吧!

相关问题