package jdbc.utils;
import java.sql.*;
/*
JDBC工具类,简化JDBC编程 注册驱动 获取连接
*/
public class DBUtil {
/**
* 工具类中的构造方法都是私有的。
* 因为工具类当中的方法都是静态的,不需要new对象,直接采用类名调用
*/
private DBUtil(){}
// 静态代码块在类加载时执行,并且只执行一次。
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
*
* @return 连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException{
return DriverManager.getConnection("jdbc:mysql://localhost:3306/jdbc", "root","root");
}
/**
* 关闭资源
* @param conn 连接对象
* @param stmt 数据库操作对象
* @param rs 结果集
*/
public static void close(Connection conn, Statement stmt, ResultSet rs){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
调用工具类
package jdbc;
import jdbc.utils.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* 这个程序开启一个事务,这个事务专门进行查询,并且使用行级锁/悲观锁锁住相关的记录。
*/
public class JDBCTest13 {
public static void main(String[] args) {
Connection conn=null;
PreparedStatement ps=null;
ResultSet rs=null;
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);// 开启事务
String sql="select deptno,dname,loc from dept where dname= ? for update";
ps=conn.prepareStatement(sql);
ps.setString(1,"研A发一部");
rs=ps.executeQuery();
while (rs.next()){
System.out.println(rs.getString("deptno")+", "+rs.getString("dname")+", "+rs.getString("loc"));
}
conn.commit();// 提交事务(事务结束)
} catch (SQLException e) {
if (conn != null) {
try {
conn.rollback();//回滚事务(事务结束)
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
}finally {
DBUtil.close(conn,ps,rs);
}
}
}