【发布时间】:2013-10-21 09:00:02
【问题描述】:
下面提到了带有和不带有事务的我的 jdbc 程序代码。
没有 JDBC 中的事务
stmt = conn.createStatement();
System.out.println("creating statement....");
String sql;
sql = " INSERT INTO testing VALUES (3, 'Rita', 'Tez','vizag')";
stmt.executeUpdate(sql);
System.out.println("deleted.....");
sql = "SELECT s_no,s_name,s_group,s_area from testing group by s_no,s_name,s_group, s_area";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
String s_name = rs.getString("s_name");
System.out.println("employees names:" +s_name);
}
在 JDBC 中使用事务
conn.setAutoCommit(false);
System.out.println("Creating statement...");
stmt = conn.createStatement(
ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_UPDATABLE);
System.out.println("Inserting one row....");
String SQL = "INSERT INTO testing " +
"VALUES (3, 'Rita', 'Tez','vizag')";
stmt.executeUpdate(SQL);
SQL = "INSERT INTO testing " +
"VALUES (4, 'Sita', 'Singh','hyd')";
stmt.executeUpdate(SQL);
System.out.println("Commiting data here....");
conn.commit();
String sql = "SELECT s_no,s_name,s_group,s_area FROM testing group by s_no,s_name,s_group,s_area ";
ResultSet rs = stmt.executeQuery(sql);
System.out.println("List result set for reference....");
printRs(rs);
rs.close();
stmt.close();
conn.close();
}catch(SQLException se){
se.printStackTrace();
System.out.println("Rolling back data here....");
try{
if(conn!=null)
conn.rollback();
}catch(SQLException se2){
se2.printStackTrace();
}
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
stmt.close();
}catch(SQLException se2){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
public static void printRs(ResultSet rs) throws SQLException{
rs.beforeFirst();
while(rs.next()){
int s_no = rs.getInt("s_no");
String s_name = rs.getString("s_name");
String s_group = rs.getString("s_group");
String s_area = rs.getString("s_area");
System.out.print("s_no: " + s_no);
System.out.print(", s_name: " + s_name);
System.out.print(", s_group: " + s_group);
System.out.println(", s_area: " + s_area);
}
System.out.println();
}
}
两个交易都返回相同的结果,然后我们在JDBC 中使用TRANSACTIONS。请澄清我的疑问。
【问题讨论】:
-
与您在数据库的任何其他用途中使用事务的原因相同。将一组语句作为一个单元提交或回滚。
标签: java sql jdbc transactions