1、private static Connection conn=null;//多个线程共享变量,所以线程不安全的:
解决方法:可以做线程同步,但是又会存在线程瓶颈问题(系统运行的很慢)。
应该实现:一个线程有自己的独有的连接,一个线程有一各连接(自己可以复用)。
package util;
import common.RowMapper;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DbUtils {
private static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private static final String JDBC_URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
private static final String JDBC_USERNAME="root";
private static final String JDBC_PASSWORD="123456";
//private static Connection conn=null;//多个线程共享变量,所以线程不安全的 HashMap<线程,连接>
private static ThreadLocal<Connection> local=new ThreadLocal<Connection>();
//1、加载驱动用静态块来实现,自动调用
static{
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
}
//2、打开连接
public static Connection openConnection(){
Connection conn=local.get();//取连接
try {
if(conn==null||conn.isClosed()){
conn= DriverManager.getConnection(JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD);
local.set(conn);//,没有连接,就放连接
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 执行DML操作
* @param sql
* @param params
* @return
*/
public static int update(String sql,Object...params){//Object...params为可变参数
Connection conn=openConnection();//打开连接
int row=0;
PreparedStatement pst=null;
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
}
row=pst.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行DML异常",e);
}finally{
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return row;
}
/**
* 执行查询操作
* @param sql
* @param params
* @return
*/
public static List<Map<String,Object>> query(String sql, Object...params){
Connection conn=openConnection();//打开连接
ResultSet rs=null;
PreparedStatement pst=null;
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
} }
rs=pst.executeQuery();//查询之后返回一个结果集
//解析结果集
//首先获取rs里面的元数据
ResultSetMetaData rsmd= rs.getMetaData();
int count=rsmd.getColumnCount();//得到列的总数
while(rs.next()){
Map<String,Object> row=new HashMap<String,Object>();
//具体解析
for(int i=0;i<count;i++){
String columnLabel=rsmd.getColumnLabel(i+1);//得到列的名字
row.put(columnLabel,rs.getObject(columnLabel));
}
list.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行查询异常",e);
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
/**
* 执行查询,利用RowMapper
* @param sql
* @param rowMapper
* @param params
* @param <T>
* @return
*/
public static <T> List<T> query(String sql, RowMapper<T> rowMapper, Object...params){
Connection conn=openConnection();//打开连接
ResultSet rs=null;
PreparedStatement pst=null;
List<T> list=new ArrayList<T>();
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
} }
rs=pst.executeQuery();//查询之后返回一个结果集
while(rs.next()){
T entity= rowMapper.mapping(rs);//解析完以后返回一个实体对象
list.add(entity);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行查询异常",e);
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
/**
* 关闭连接
*/
public static void close(){
Connection conn=local.get();
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
local.remove();
conn=null;
}
}
}
import util.DbUtils;
public class Test3 {
public static void main(String[] args) {
DbUtils.update("delete from `order1` where id=?",1);
DbUtils.close();
}
}
2、添加事务:
package util;
import common.RowMapper;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class DbUtils {
private static final String JDBC_DRIVER="com.mysql.jdbc.Driver";
private static final String JDBC_URL="jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8&useSSL=false";
private static final String JDBC_USERNAME="root";
private static final String JDBC_PASSWORD="123456";
//private static Connection conn=null;//多个线程共享变量,所以线程不安全的 HashMap<线程,连接>
private static ThreadLocal<Connection> local=new ThreadLocal<Connection>();
//1、加载驱动用静态块来实现,自动调用
static{
try {
Class.forName(JDBC_DRIVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("驱动加载失败");
}
}
//2、打开连接
public static Connection openConnection(){
Connection conn=local.get();//取连接
try {
if(conn==null||conn.isClosed()){
conn= DriverManager.getConnection(JDBC_URL,JDBC_USERNAME,JDBC_PASSWORD);
local.set(conn);//,没有连接,就放连接
}
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/*
* 开启事务
* */
public static void beginTransaction(){
Connection conn=openConnection();//打开连接
try {
conn.setAutoCommit(false);//设置为手动提交
} catch (SQLException e) {
e.printStackTrace();
}
}
//提交事务
public static void commit(){
Connection conn=local.get();//取出当前连接
try {
conn.commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
/*
* 回滚
* */
public static void rollback(){
Connection conn=local.get();//取出当前连接
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 执行DML操作
* @param sql
* @param params
* @return
*/
public static int update(String sql,Object...params){//Object...params为可变参数
Connection conn=openConnection();//打开连接
int row=0;
PreparedStatement pst=null;
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
}
row=pst.executeUpdate();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行DML异常",e);
}finally{
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return row;
}
/**
* 执行查询操作
* @param sql
* @param params
* @return
*/
public static List<Map<String,Object>> query(String sql, Object...params){
Connection conn=openConnection();//打开连接
ResultSet rs=null;
PreparedStatement pst=null;
List<Map<String,Object>> list=new ArrayList<Map<String,Object>>();
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
} }
rs=pst.executeQuery();//查询之后返回一个结果集
//解析结果集
//首先获取rs里面的元数据
ResultSetMetaData rsmd= rs.getMetaData();
int count=rsmd.getColumnCount();//得到列的总数
while(rs.next()){
Map<String,Object> row=new HashMap<String,Object>();
//具体解析
for(int i=0;i<count;i++){
String columnLabel=rsmd.getColumnLabel(i+1);//得到列的名字
row.put(columnLabel,rs.getObject(columnLabel));
}
list.add(row);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行查询异常",e);
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
/**
* 执行查询,利用RowMapper
* @param sql
* @param rowMapper
* @param params
* @param <T>
* @return
*/
public static <T> List<T> query(String sql, RowMapper<T> rowMapper, Object...params){
Connection conn=openConnection();//打开连接
ResultSet rs=null;
PreparedStatement pst=null;
List<T> list=new ArrayList<T>();
try {
pst=conn.prepareStatement(sql);
if(params!=null&¶ms.length>0){
for(int i=0;i<params.length;i++){
pst.setObject(i+1,params[i]);
} }
rs=pst.executeQuery();//查询之后返回一个结果集
while(rs.next()){
T entity= rowMapper.mapping(rs);//解析完以后返回一个实体对象
list.add(entity);
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException("执行查询异常",e);
}finally{
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(pst!=null){
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return list;
}
/**
* 关闭连接
*/
public static void close(){
Connection conn=local.get();
if(conn!=null){
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
local.remove();
conn=null;
}
}
}
import util.DbUtils;
public class Test3 {
public static void main(String[] args) {
DbUtils.beginTransaction();//开启事务
try{
DbUtils.update("delete from `order1` where id=?",2);
DbUtils.update("delete from `order1` where id=?",3);//有异常
DbUtils.commit();//手动提交一下才有数据
}catch (Exception ex){
DbUtils.rollback();
}
DbUtils.close();
}
}
2、不开启事务:
import util.DbUtils;
public class Test3 {
public static void main(String[] args) {
/* DbUtils.beginTransaction();//开启事务
try{
DbUtils.update("delete from `order1` where id=?",2);
DbUtils.update("delete from `order1` where id=?",3);//有异常
DbUtils.commit();//手动提交一下才有数据
}catch (Exception ex){
DbUtils.rollback();
}
DbUtils.close();*/
DbUtils.update("delete from `order1` where id=?",4);
DbUtils.update("deletes from `order1` where id=?",5);
DbUtils.close();
}
}