JDBC使用事务实例
时间:2021-07-01 10:21:17
帮助过:3人阅读
import java
.sql.*
public class useTransaction {
public static void main(String[] args) {
// TODO Auto-generated method stub
Connection conn = null
Statement
st = null
PreparedStatement pst = null
ResultSet rs = null
Savepoint sp = null
try{
conn = JDBC_Connection
.getConnection()
//指定事务隔离级别
conn
.setTransactionIsolation(conn
.TRANSACTION_READ_UNCOMMITTED)
pst = conn
.prepareStatement(
"create table users (id smallint,username text)")
pst
.execute()
//提交事务
conn
.commit()
pst
.close()
}catch(SQLException e){
System
.err.println(
"连接数据库或者建表失败")
System
.err.println(
"事务回滚到回滚点")
try{
conn
.rollback()
}catch(SQLException ex){
//ex
.printStackTrace()
System
.out.println(
"回滚失败")
}
try{
conn
.setSavepoint()
st = conn
.createStatement()
st.executeUpdate(
"insert into users values(110,‘Janes‘)")
//
st.executeUpdate(
"insert into users values(‘shibai‘,‘Janes‘)")
conn
.commit()
conn
.releaseSavepoint(sp)
st.close()
conn
.close()
}catch(SQLException et){
System
.err.println(
"操作失败")
System
.err.println(
"事务回滚到存储点")
try{
conn
.rollback(sp)
st.close()
conn
.close()
}catch(SQLException exc){
System
.out.println(
"回滚到存储点失败")
//exc
.printStackTrace()
}
//et
.printStackTrace()
}
//e
.printStackTrace()
}
}
}
JDBC使用事务实例
标签: