我是靠谱客的博主 清脆酒窝,最近开发中收集的这篇文章主要介绍多线程共用一个Connection插入数据如题,测试多线程共用一个Connection是否会影响sql语句的执行结果 ,觉得挺不错的,现在分享给大家,希望可以做个参考。
概述
如题,测试多线程共用一个Connection是否会影响sql语句的执行结果
package com.zw.mgt;
import org.junit.Test;
import org.voovan.dbutil.DbOperate;
import org.voovan.tools.TSQL;
import org.voovan.tools.log.Logger;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class ThreadTest {
@Test
public void test() throws InterruptedException, SQLException {
DbOperate dbOperate = new DbOperate();
Connection connection = dbOperate.getConnection();
ThreadDemo threadDemo1 = new ThreadDemo(connection);
ThreadDemo threadDemo2 = new ThreadDemo(connection);
ThreadDemo threadDemo3 = new ThreadDemo(connection);
ThreadDemo threadDemo4 = new ThreadDemo(connection);
ThreadDemo threadDemo5 = new ThreadDemo(connection);
ThreadDemo threadDemo6 = new ThreadDemo(connection);
ThreadDemo threadDemo7 = new ThreadDemo(connection);
ThreadDemo threadDemo8 = new ThreadDemo(connection);
ThreadDemo threadDemo9 = new ThreadDemo(connection);
ThreadDemo threadDemo10 = new ThreadDemo(connection);
threadDemo1.start();
threadDemo2.start();
threadDemo3.start();
threadDemo4.start();
threadDemo5.start();
threadDemo6.start();
threadDemo7.start();
threadDemo8.start();
threadDemo9.start();
threadDemo10.start();
Thread.sleep(1000*60*5);
}
public class ThreadDemo extends Thread{
public ThreadDemo(Connection connection){
this.connection = connection;
}
private Connection connection;
public void run(){
for (int i = 0; i < 100; i++) {
PreparedStatement preparedStatement = null;
try {
preparedStatement = TSQL.createPreparedStatement(connection, "insert into test values(""+Thread.currentThread().getName()+":"+i+"")", null);
preparedStatement.executeUpdate();
} catch (SQLException e) {
Logger.error("Update excution SQL Error!n" ,e);
}
}
}
}
}
执行结果:
插入1000条数据。所以sql语句执行应该具有原子性。
最后
以上就是清脆酒窝为你收集整理的多线程共用一个Connection插入数据如题,测试多线程共用一个Connection是否会影响sql语句的执行结果 的全部内容,希望文章能够帮你解决多线程共用一个Connection插入数据如题,测试多线程共用一个Connection是否会影响sql语句的执行结果 所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复