JDBC对Mysql事务的控制

1. 开启事务
connection.setAutoCommit(false);
2. 回滚事务
connection.rollback();
3. 提交事务
connection.commit();
4. 具体案例代码
package zhi.itlearn.dao.impl;import zhi.itlearn.dao.IStudentDao;import zhi.itlearn.domain.Student;import zhi.itlearn.utils.JDBCUtils;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.sql.SQLException;import java.util.ArrayList;import java.util.List;public class IStudentDaoImpl implements IStudentDao {    public List<Student> findAll(){        Connection connection = null;        PreparedStatement statement = null;        ResultSet resultSet = null;        List<Student> list = new ArrayList<Student>();        try{            connection = JDBCUtils.getConnection();//JDBCUtils是一个自定义工具类,代码见另一篇博客             //开启事务            connection.setAutoCommit(false);            statement = connection.prepareStatement("SELECT * FROM student WHERE sage = ?");            statement.setObject(1,"19");            resultSet = statement.executeQuery();            while (resultSet.next()){                Student student = new Student();                student.setSno(resultSet.getString("sno"));                student.setSage(resultSet.getInt("sage"));                student.setSname(resultSet.getString("sname"));                list.add(student);            }            //事务提交            connection.commit();        }catch (Exception ex){            try {                if(connection!=null)                connection.rollback();            } catch (SQLException e) {                e.printStackTrace();            }        }finally {            JDBCUtils.close(resultSet,statement,connection);            return list;        }    }}
©著作权归作者所有:来自51CTO博客作者Eternal_Summer的原创作品,如需转载,请注明出处,否则将追究法律责任

更多相关文章

  1. Python使用pdb更优雅的调试代码
  2. 手把手教你调试代码并使用Echarts进行数据可视化
  3. PHP自定义函数+系统函数库(代码示例)
  4. 如何将smarty安装到MVC架构中(代码示例)
  5. PHP 跨域之header函数(代码示例)
  6. PHP+Ajax实现文章心情投票功能(代码实例)
  7. PHP+jQuery开发简单翻牌抽奖的功能(代码实例)
  8. PHP-Curl模拟HTTPS请求(代码实例)
  9. PHP使用递归按层级查找数据(代码详解)

随机推荐

  1. android TextView 文本过长时用滚动条显
  2. Android(安卓)viewPage notifyDataSetCha
  3. android:网路检测
  4. android 傻瓜式 MultiDex 插件,从此再也不
  5. 一个android参考网站,工具+源码
  6. minSdkVersion各个版本号对应android版本
  7. android源码下载-等待提示动画
  8. centos下安装adb环境
  9. android:inputType参数类型说明
  10. Android通过PHP连接MySQL(传值查询)