ThreadLocal+JDBC+表引擎,使setAutoCommit(false)无效?

问题:

源代码

public class JDBCTools {//一个JDBC工具类
 	private static ThreadLocal<Connection> th;
	 static {
    //静态代码块完成连接池的初始化
     th=new ThreadLocal<>();
     }
    //获取连接
 	public static Connection getConnection() throws SQLException {
        Connection c = th.get();//获取当前线程中的连接对象
        if (c==null)//
        {
            c=ds.getConnection();
            th.set(c);
        }
        return c;
    }
       //关闭连接
 	public static void close() throws SQLException {
        Connection c = th.get();
        if (c!=null) {
            c.close();
            th.remove();
        }
        c.close();
    }
   //更新操作
 	public static int update3(String sql,Object...args) throws SQLException {
        Connection connection = getConnection();//获取当前线程的连接对象
        PreparedStatement pre = connection.prepareStatement(sql);//sql语句对象
        if (args!=null&&args.length>0)
        for (int i=0;i<args.length;i++) {
            pre.setObject(i+1,args[i]);
        }
        int i = pre.executeUpdate();
        pre.close();
        return i;
    }
 }

测试代码

public static void main(String[] args) throws SQLException {
        String sql1="update example set text=? where id=?";
        String sql2="update example set text=?  id=?";	//故意错误,造成事务无法提交

        Connection c = JDBCTools.getConnection();
        c.setAutoCommit(false);
      try {
          JDBCTools.update3(sql1, "111", 1);
          JDBCTools.update3(sql2, "222", 2);
          c.commit();
      }catch (Exception e)
      {
          e.printStackTrace();
          c.rollback();
      }
        c.setAutoCommit(true);
        JDBCTools.close();
    }

数据库数据:
在这里插入图片描述

第一次执行结果:
在这里插入图片描述
发现,第一个记录竟然改变了,明明自己设置了setAutoCommit(false);

原因:

数据库的引擎如果是innodb, 不执行commit,数据不会更新;如果用的是myisam引擎,因为不支持事务,不执行commit,也会更新数据。

发现:自己使用的是MyISAM引擎。故修改为Innodb解决问题…
表引擎修改的SQL语句:alter table 表名 engine=innodb;
在这里插入图片描述笔记内容,仅供参考

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值