mysql与executorservice

zynd9foi  于 2021-06-18  发布在  Mysql
关注(0)|答案(1)|浏览(364)

我想使用executors加速将可用数据列表导入数据库

public static void main(String[] args) {

            methodOpenDatabaseConnection();

                        ExecutorService newFixedThreadPool = Executors.newScheduledThreadPool(100);

                        for (long i = 0; i < 1000; i++) {
                            newFixedThreadPool.execute(new Runnable() {
                                @Override
                                public void run( {
methodSaveDataToDatabaseMysql();
                                }
                            });
                        }

                       newFixedThreadPool.shutdown();
                       newFixedThreadPool.shutdown();
                       newFixedThreadPool.awaitTermination(60, TimeUnit.SECONDS);
                       if (newFixedThreadPool.isShutdown()) {
                          methodCloseConnectionDatabase();
                      }
                    }

        public void methodSaveDataToDatabaseMysql() {
                try {
                    preparedStatement = connection.prepareStatement("INSERT INTO `demo`"
                            + " (`name`,`name2`,`name3`) VALUES (?,?,?)");
                    preparedStatement.setString(1, "name1");
                    preparedStatement.setString(2, "name2");
                    preparedStatement.setString(3, "name3");
                    preparedStatement.executeUpdate();
                } catch (SQLException ex) {
                    Logger.getLogger(WebsiteResourcesImpl1.class.getName()).log(Level.SEVERE, null, ex);
                }
            }

如果我在save方法中添加synchronized,它将生成一个错误。它将成功,但速度没有提高

java.sql.SQLException: No value specified for parameter 3
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:569)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:537)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:527)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:512)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:480)
    at com.mysql.cj.jdbc.PreparedStatement.checkAllParametersSet(PreparedStatement.java:2159)

我认为save语句没有问题,因为它仍然可以成功地保存数据,但在executorservice中不稳定

jei2mxaa

jei2mxaa1#

基于此代码 preparedStatement = connection.prepareStatement... 那么 preparedStatement 不是线程安全的。
考虑让它成为当地的 methodSaveDataToDatabaseMysql 方法

相关问题