我的原代码:
我定义两个方法,两个方法中我都是用插入的语句:
public void insertUser(){
Class.forName("com.mysql.jdbc.Driver");
Connection conn=null;
prepareStatement pst=null;
try{
conn=DriverManeger.getConnection("jdbc:mysql://localhost:8080/test","root","root");//这里不建议这样写,但是为了我的代码的完整性,我这里还是先这样写了,应该建立一个//utils包,里面有我们需要调用的getconnection方法,这样我们的代码就不会有那么多的重复了;
pst=conn.prepareStatement()
int count=pst.executeUpdate("insert into user(id,name,password,age,email) values(001,huang,22,xxx)");
system.out.println("插入用户表的数据量为"+count);
}catch(Exception ex){
ex.PrintStackTrace();
}
}
public void insertAddress(){
Class.forName("com.mysql.jdbc.Driver");
Connection conn=null;
prepareStatement pst=null;
try{
conn=DriverManeger.getConnection("jdbc:mysql://localhost:8080/test","root","root");//这里不建议这样写,但是为了我的代码的完整性,我这里还是先这样写了,应该建立一个//utils包,里面有我们需要调用的getconnection方法,这样我们的代码就不会有那么多的重复了;
pst=conn.prepareStatement()
int count=pst.executeUpdate("insert into address(id,city,country,user_id) values(001,shanghai,china,10)");
system.out.println("插入地址表的用户量为"+count);
}catch(Exception ex){
ex.PrintStackTrace();
}
}
main方法中调用两个方法:
public static void main(String[] args){
insertUser();
insertAddress();
}
这里进行处理时输出的结果是:
插入用户表的数据量为:5
然后是报错了;;;
问题的解决办法是我们使用事物处理的方法
同样是使用两个方法,但是我们将其使用连接的setAutoCommit方法,且设置其属性为false;
所以我们这样修改:
将两个方法设置参数(connection conn)且抛出sqlException异常;
然后在main方法中修改为:
connection con=null
try{
con=getConnection()//好累,这里偷懒了,直接调用,懂了就行;
con.setAutoCommit(false);//将其设置为不自动提交
insertUser(con);
insertAddress(con);
con.commit();//提交所有执行;}catch(Exception ex){
system.out.println("捕获到异常");
ex.PrintStackTrace();
try{
con.rollback();//事务有一件没有完成就进行回滚;
system.out.println("事务回滚");
}
catch(Exception ex){
ex.PrintStackTrace();
}
添加一句,我的close()都没写的,自行添加;