對於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的話可能會導致其他線程中不希望提交的事物提交