
* JDBC
* @author IT学习者
*
*@url itxxz. com/a/javashili/
*
*/
public class DBConnection {
/**
* 驱动类名称
*/
private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver"
/**
* 数据库连接字符串
*/
private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/itxxz"
/**
* 数据库用户名
*/
private static final String USER_NAME = "root"
/**
* 数据库密码
*/
private static final String PASSWORD = "root"
/**
* 数据库连接类
*/
private static Connection conn
/**
* 数据库 *** 作类
*/
private static Statement stmt
private static PreparedStatement pst
private static ResultSet rs
private static final String DELETE_USERS = "DELETE FROM USERS
// 加载驱动
static{
try {
Class.forName(DRIVER_CLASS)
} catch (Exception e) {
System.out.println("加载驱动错误")
System.out.println(e.getMessage())
}
}
// 取得连接
private static Connection getConnection(){
try {
conn = DriverManager.getConnection(DATABASE_URL, USER_NAME, PASSWORD)
} catch (Exception e) {
System.out.println("取得连接错误")
System.out.println(e.getMessage())
}
return conn
}
/**
* 关闭链接
*/
public static void close(){
try {
if(pst != null){
pst.close()
pst = null
}
if(stmt != null){
stmt.close()
stmt = null
}
if(conn != null){
conn.close()
conn = null
}
if(rs != null){
rs.close()
rs = null
}
} catch (SQLException e) {
System.out.println("连接关闭异常")
}
}
/**
* 删除
*/
public static int deleteUsers(){
try {
pst = conn.prepareStatement(DELETE_USERS)
return pst.executeUpdate()
} catch (Exception e) {
System.out.println(e.getMessage())
return 0
}finally{
close()
}
}
下面,将利用MySQL的客户端程序,分别测试几种隔离级别。测试数据库为test,表为tx;表结构:
id int
num
int
两个命令行客户端分别为A,B;不断改变A的隔离级别,在B端修改数据。
(一)、将A的隔离级别设置为read uncommitted(未提交读)
在B未更新数据之前:
客户端A:
B更新数据:
客户端B:
客户端A:
经过上面的实验可以得出结论,事务B更新了一条记录,但是没有提交,此时事务A可以查询出未提交记录。造成脏读现象。未提交读是最低的隔离级别。
(二)、将客户端A的事务隔离级别设置为read committed(已提交读)
在B未更新数据之前:
客户端A:
B更新数据:
客户端B:
客户端A:
经过上面的实验可以得出结论,已提交读隔离级别解决了脏读的问题,但是出现了不可重复读的问题,即事务A在两次查询的数据不一致,因为在两次查询之间事务B更新了一条数据。已提交读只允许读取已提交的记录,但不要求可重复读。
欢迎分享,转载请注明来源:内存溢出
微信扫一扫
支付宝扫一扫
评论列表(0条)