您的位置:首页 > 其它

JDBC事务处理

2012-03-01 15:06 155 查看
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Statement;

import com.neusoft.java275.dao.DBUtil;

public class Transaction
{
private static boolean exceptionFlag=true;
public static void main(String[] args)
{
Connection con = null;
Statement stmt = null;
PreparedStatement prestmt = null;
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:@192.168.137.23:1521:orcl", "java", "java");
con.setAutoCommit(false);
stmt = con.createStatement();
int code = stmt.executeUpdate("insert into student(id,name) values(student_seq.nextval,'张阳')");
System.out.println("受影响的行数:" + code);
if(exceptionFlag)
{
throw new RuntimeException("人为异常");
}
prestmt = con.prepareStatement("update student set name=? where name=?");
prestmt.setString(1, "张 阳_updated");
prestmt.setString(2, "张阳");
code = prestmt.executeUpdate();
System.out.println("受影响的行数:" + code);
con.commit();
}
catch (Exception e)
{
try
{
con.rollback();
}
catch (SQLException e1)
{
e1.printStackTrace();
}
e.printStackTrace();
}
finally
{
try
{
con.setAutoCommit(true);
}
catch (SQLException e)
{
e.printStackTrace();
}
DBUtil.closeQuietly(stmt);
DBUtil.closeQuietly(prestmt);
DBUtil.closeQuietly(con);

}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: