JDBC对Mysql事务的控制

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;
        }
    }
}

猜你喜欢

转载自blog.csdn.net/qq_42278320/article/details/112972324