多线程共用一个Connection插入数据

如题,测试多线程共用一个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语句执行应该具有原子性。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值