问题:
源代码
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;
笔记内容,仅供参考