主函数
路径:src\com\lzm\Main.java
package com.lzm;
import com.lzm.jdbc.Demo;
import com.lzm.jdbc.Demo_transaction;
import com.lzm.pojo.Role;
import java.util.List;
import java.util.Scanner;
public class Main {
public static void main(String[] args) throws Exception {
Scanner scanner = new Scanner(System.in);
System.out.println("请输入:1、S 2、I 3、U 4、D 5、T");
String str = scanner.nextLine(); // 读取一行字符串
Demo demo = new Demo();
Demo_transaction demo_transaction = new Demo_transaction();
if ("1".equals(str)) {
//查询所有
System.out.println("select");
List<Role> roles = demo.selectAll();
System.out.println(roles);
} else if ("2".equals(str)) {
//添加一个元素
System.out.println("insert");
int count = demo.insert(new Role(3, "lzm"));
System.out.println(count);
} else if ("3".equals(str)) {
//修改一个元素
System.out.println("update");
int count = demo.update(new Role(3, "lyl"));
System.out.println(count);
} else if ("4".equals(str)) {
System.out.println("delete");
int count = demo.delete(3);
System.out.println(count);
} else if ("5".equals(str)) {
System.out.println("事务");
demo_transaction.transaction();
} else {
System.out.println("------------------------------------");
}
}
}
Demo_transaction(事务)
路径:src\com\lzm\jdbc\Demo_transaction.java
package com.lzm.jdbc;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.Statement;
import java.util.Properties;
public class Demo_transaction {
public void transaction() throws Exception {
//注册驱动
//Class.forName("com.mysql.jdbc.Driver");
//设置参数
String url = "jdbc:mysql:///space_01?useSSL=false&useServerPrepStmts=true";
String username = "root";
String password = "admin";
//获取数据库连接
Connection connection = DriverManager.getConnection(url, username, password);
//定义数据库
String sql1 = "update t_role set roleName = 'aaa' where id = 3";
String sql2 = "update t_role set roleName = 'bbb' where id = 4";
//获取执行sql的statement对象
Statement statement = connection.createStatement();
try {
//开启事务
connection.setAutoCommit(false);
//执行sql1
int count1 = statement.executeUpdate(sql1);
//处理结果
System.out.println("count1 = " + count1);
//设置异常
int i = 3 / 0;
//执行sql2
int count2 = statement.executeUpdate(sql2);
System.out.println(count2);
//提交事务
connection.commit();
} catch (Exception e) {
//回滚事务
connection.rollback();
e.printStackTrace();
}
//关闭资源
statement.close();
connection.close();
}
}
执行前数据库t_role表
执行结果:控制台
执行结果:数据库t_role表