Java数据库——事务处理
在数据库中执行5条SQL语句,这些SQL语句本身需要保持一致,即要么同时成功,要么同时失败
事务基本操作
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.sql.*; import java.text.SimpleDateFormat; import java.util.Scanner; public class JDBC20_demo { //定义MySQL的数据库驱动程序 public static final String DBDRIVER = "org.gjt.mm.mysql.Driver"; //定义MySQL数据库的连接地址 public static final String DBURL = "jdbc:mysql://localhost:3306/mysql_demo"; //MySQL数据库的连接用户名 public static final String DBUSER = "root"; //MySQL数据库的连接密码 public static final String DBPASS = "123456"; public static void main(String[] args) throws Exception{ // TODO 自动生成的方法存根 Connection conn = null; //数据库连接 Statement stmt = null; //数据库操作 Class.forName(DBDRIVER); //加载驱动程序 //连接MySQL数据库时,要写上连接的用户名和密码 conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS); conn.setAutoCommit(false); //取消自动提交 //实例化PreparedStatement stmt = conn.createStatement(); //实例化对象 //加入5条SQL语句 stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')"); stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')"); stmt.addBatch("INSERT INTO user(name1,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')"); stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')"); stmt.addBatch("INSERT INTO user(name,password,age,sex,birthday)"+"VALUES('lisi','lisimima',14,'男','1987-09-23')"); try{ int temp[] = stmt.executeBatch(); //批量执行 System.out.println("更新了"+temp.length+"条数据。"); conn.commit(); //提交事务 }catch(Exception e){ try{ conn.rollback(); }catch(Exception ex){ ex.printStackTrace(); } } stmt.close(); conn.close(); } public static void print(ResultSet rs,int re) throws Exception{ if(re>0){ rs.next(); //由前向后输出 }else{ rs.previous(); //有后向前输出 } int id = rs.getInt(1); String name = rs.getString(2); String pass = rs.getString(3); int age = rs.getInt(4); String sex = rs.getString(5); java.util.Date d = rs.getDate(6); System.out.println("编号:"+ id); System.out.println("姓名:"+name); System.out.println("密码:"+pass); System.out.println("年龄:"+age); System.out.println("性别:"+sex); System.out.println("生日:"+d); } }
本文只发表于博客园和tonglin0325的博客,作者:tonglin0325,转载请注明原文链接:https://www.cnblogs.com/tonglin0325/p/5306526.html