[java]代码库
package mysql2;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestCommit {
private static Connection con = null;
private static ResultSet result=null;
private static PreparedStatement pre =null;
public static void main(String[] args) {
//1.加载数据库驱动
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
System.out.println("加载失败!");
e.printStackTrace();
}
System.out.println("加载成功!");
//2.连接数据库
try {
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db_library", "root", "123");
} catch (SQLException e) {
System.out.println("连接数据库失败!");
e.printStackTrace();
}
System.out.println("成功连接数据库!");
//3.执行sql语句语句的PreparedStatement,然后执行sql语句
/*
* update useraccount set totalmoney=totalmoney-1000 where name='李四'
* update useraccount set totalmoney=totalmoney+1000 where name='王二'
*/
/*try {
String name1="李四";
pre=con.prepareStatement("update useraccount set totalmoney=totalmoney-1000 where name=?");
pre.setString(1, name1);
int result =pre.executeUpdate();
System.out.println(result);
} catch (SQLException e1) {
e1.printStackTrace();
}
//模拟数据库出现故障:死机、服务器出现问题,是认为控制不了的
Integer.parseInt("kbq");//无法将kbq转成整数,肯定会报错
try {
String name2="王二";
pre=con.prepareStatement("update useraccount set totalmoney=totalmoney+1000 where name=?");
pre.setString(1, name2);
int result = pre.executeUpdate();
System.out.println(result);
} catch (SQLException e1) {
e1.printStackTrace();
}*/
try{
//设置手工提交
con.setAutoCommit(false);
String name1="李四";
pre=con.prepareStatement("update useraccount set totalmoney=totalmoney-1000 where name=?");
pre.setString(1, name1);
int result =pre.executeUpdate();
System.out.println(result);
//模拟数据库出现故障:死机、服务器出现问题,是认为控制不了的
Integer.parseInt("kbq");//无法将kbq转成整数,肯定会报错
String name2="王二";
pre=con.prepareStatement("update useraccount set totalmoney=totalmoney+1000 where name=?");
pre.setString(1, name2);
int result1 = pre.executeUpdate();
System.out.println(result1);
//提交事务
con.commit();
}catch (SQLException e1) {
try {
con.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
e1.printStackTrace();
}
//4.释放数据库的资源
finally{
try {
if(result!=null)
result.close();
if(pre!=null)
pre.close();
if(con!=null)
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
System.out.println("执行成功!");
}
}