Java处理数据库的事务疑问,麻烦大家:)

dukcho 2004-04-08 05:01:02
我想一次性完成两个操作:
1,删除Student中一个班的数据的数据;
2,向Student中添加一个班的新的数据;
两个操作要么都成功,要么都不成功。这应该作为一个事务吧,但我不知道Java中对数据库中的事务应该如何处理,请高手指教,谢谢!!
...全文
41 3 打赏 收藏 转发到动态 举报
写回复
用AI写文章
3 条回复
切换为时间正序
请发表友善的回复…
发表回复
seawolfzxw 2004-04-08
  • 打赏
  • 举报
回复
学习
bs221cn 2004-04-08
  • 打赏
  • 举报
回复
cn.setAutoCommit(false);
try{
s.excuteUpdate("update.....1");
s.excuteUpdate("update.....2");
cn.commit();
}
catch(SQLException e)
{
cn.rollback();
}

loveflea 2004-04-08
  • 打赏
  • 举报
回复
流程是这样的
set autocommit = 0;
delete from student ...;
insert into student ...;
commit;
set autocomit = 1;



给你个例子:
import java.sql.*;

public class Test
{
public static void main(String[] args)
{
try
{
String query = "";

// Load Mysql's JDBC Driver
String driver="com.mysql.jdbc.Driver";
Class.forName(driver).newInstance();

// Remote mysql server of SiChuan
String url = "jdbc:mysql://localhost:3306/db?useUnicode=true&characterEncoding=gbk";
String user = "root";
String password = "password";
Connection connRemoteMysql = DriverManager.getConnection(url, user, password);

// set AutoCommit = false
connRemoteMysql.setAutoCommit(false);

// Define Statement
Statement stmt = connRemoteMysql.createStatement();

query = "delete from Student where class=5";
stmt.executeUpdate(query);
query = "insert into student(...) values(...)";
stmt.executeUpdate(query);

// commit the translate
connRemoteMysql.commit();

if (stmt!=null){
stmt.close();
}
if (connRemoteMysql!=null){
connRemoteMysql.close();
}

}
catch (Exception e) {
e.printStackTrace();
try {
if (connRemoteMysql != null && !connRemoteMysql.isClosed())
{
prt("Rolling back transaction");
connRemoteMysql.rollback();
}
}
catch(SQLException rx) {
System.out.println("SQLException - rollback() failed: " + rx.getMessage());
}
}
finally {
if (connRemoteMysql != null && !connRemoteMysql.isClosed()) {
connRemoteMysql.setAutoCommit(true);
}
}
}
}

56,679

社区成员

发帖
与我相关
我的任务
社区描述
MySQL相关内容讨论专区
社区管理员
  • MySQL
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧