JDBC多线程多个statement共享同一个connection

对于mysql测试案例

package 使用同一个connection;


import java.sql.Connection;

import java.sql.DriverManager;

import java.sql.ResultSet;

import java.sql.SQLException;

import java.sql.Statement;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;



public class Main {

public static void main(String[] args) {

String urlString = "";// 数据库连接命令

String usr = "meepo";// 用户名

String passwd = "meepo";// 密码

String driverString = "com.mysql.jdbc.Driver";// 连接驱动命令

urlString = "jdbc:mysql://" + "localhost:5030";

try {

Class.forName(driverString).newInstance();

} catch (InstantiationException | IllegalAccessException

| ClassNotFoundException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

Connection connection = null;

try {

connection = DriverManager.getConnection(urlString, usr, passwd);

connection.createStatement().execute("use test;");

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

ExecutorService executorService = Executors.newCachedThreadPool();

for (int i = 0; i < 1000000; i++) {

try {

final Statement statement = connection.createStatement();

executorService.execute(new Runnable() {

int k = 10;

@Override

public void run() {

// TODO Auto-generated method stub

try {

for (int j = 0; j < 109; j++) {

statement.executeUpdate("update debug set email='fuck"

+ Thread.currentThread() + new Integer(k++).toString()

+ "' where filename='item0';");

}

//while (resultSet.next()) {

//System.out.println(resultSet.getString(2));

//}

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

});

} catch (SQLException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

}

}

}

对于mysql而言在其jdbc接口中已经提供了同步方法多个线程共享同一个connection没有问题。而在实际使用中设计到事物时会出现这种情况:

由于jdbc的事物与一个connection关联在一起,因此当一个statment执行完毕需要提交时,如果调用了connection.commit()或者rollback的话可能会导致其他线程中不希望提交的事物提交

你可能感兴趣的:(java,jdbc)