2021.4.28第一次回顾:
1、什么是JDBC,就是使用java操作数据库database【Java database connectivity】
2、JDBC的本质就是一套接口,让不同数据库厂家的程序员编写一套规范,程序员在使用的时候就不需要关注是哪个品牌的数据库,只需要面向JDBC接口编程。
3、JDBC编程六步:
import java.sql.Connection;
public class JDBCTest01
{
public static void main(String[] args){
try{
//1、注册驱动
//DriverManager.registerDriver(new com.mysql.jdbc.Driver);
//把上面代码拆成两行写
Driver driver = new com.mysql.jdbc.Driver();//多态,父类型引用指向子类型对象
DriverManager.registerDriver(driver);
//2、获取连接
String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
String user = "root";
String password = "333";
Connection conn = DriverManager.getConnection(url,user,password);
//com.mysql.jdbc.JDBC4Connection@b81eda8
System.out.println("数据库连接对象"+conn);
}catch(SQLException e){
e.printStackTrace();
}
}
}
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Connection;
import java.sql.Statement;
public class JDBCTest01
{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
//1、注册驱动
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//把上面代码拆成两行写
Driver driver = new com.mysql.jdbc.Driver();//多态,父类型引用指向子类型对象
DriverManager.registerDriver(driver);
//2、获取连接
String url = "jdbc:mysql://127.0.0.1:3306/bjpowernode";
String user = "root";
String password = "333";
conn = DriverManager.getConnection(url,user,password);
//com.mysql.jdbc.JDBC4Connection@b81eda8
System.out.println("数据库连接对象"+conn);
//3、获取数据库执行对象(Statement专门执行sql语句)
stmt = conn.createStatement();
//4、执行sql语句
String sql = "insert into dept(deptno,dname,loc) values(90,'人事部','北京')";
//专门执行DML语句的(insert、delete、update)
//返回值是“影响数据库中的记录条数”,插入两条返回2,删除3条返回3
int count = stmt.executeUpdate(sql);
System.out.println(count == 1?"保存成功" :"保存失败2021/4/13");
//5、处理查询结果集
}catch(SQLException e){
e.printStackTrace();
}finally{
//6、释放资源
//为了保证资源一定释放,在finally子句中释放资源
//并且要遵从从小到大依次关闭
//分别对其try...catch
//关闭之前要判断是否为空,不为空再关闭
try{
if(stmt != null){
stmt.close();
}
}catch(SQLException e){
e.printStackTrace();
}
try{
if(conn != null){
conn.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
背代码,把这个格式理解记忆
/*
JDBC完成delete
*/
import java.sql.*;
public class JDBCTest02
{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
try{
//1、注册驱动
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取数据库执行对象
stmt = conn.createStatement();
//4、执行SQL语言
//String sql = "delete from dept where deptno=70";
String sql = "update dept set dname = 'RESEARCH',loc='DALLAS' where deptno = 20";
int count = stmt.executeUpdate(sql);
System.out.println(count == 1?"删除成功":"删除失败");
}catch(SQLException e){
e.printStackTrace();
}finally{
//6、释放资源
if(stmt != null){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*
注册驱动的另一种方式(常用方法)
*/
import java.sql.*;
public class JDBCTest03
{
public static void main(String[] args){
try{
//1、注册驱动
//这是注册驱动的第一种方式
//DriverManager.registerDriver(new com.mysql.jdbc.Driver());
//类加载的方式注册驱动【常用方法】
//为什么这种方法常用?因为参数是一个字符串,字符串可以写在xxx.properties中。
//以下方法不需要接受返回值,因为我们只需要这个类加载动作【类加载使静态代码块中的注册驱动代码执行】
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
System.out.println(conn);//com.mysql.jdbc.JDBC4Connection@b81eda8
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
/*
将连接数据库的所有信息配置到配置文件中
*/
import java.sql.*;
import java.util.*;
public class JDBCTest04{
public static void main(String[] args){
//使用资源绑定器绑定属性配置文件
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String username = bundle.getString("username");
String password = bundle.getString("password");
Connection conn = null;
Statement stmt = null;
try{
//1、注册驱动
Class.forName(driver);
//2、获取连接
conn = DriverManager.getConnection(url,username,password);
//3、获取数据库执行对象
stmt = conn.createStatement();
//4、执行SQL语言
String sql = "update dept set dname = 'RESEARCHER',loc='DALLA' where deptno = 20";
int count = stmt.executeUpdate(sql);
System.out.println(count == 1?"修改成功":"修改失败");
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}finally{
//6、释放资源
if(stmt != null){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*
处理查询结果集
ResultSet rs ;
executeQuery(sql)专门执行DQL语句的方法
*/
import java.sql.*;
import java.util.*;
public class JDBCTest05{
public static void main(String[] args){
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try{
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取数据库执行对象
stmt = conn.createStatement();
//4、执行SQL语句
//int executeUpdate(insert/delete/update)
//ResultSet executeQuery(select)
String sql = "select empno as a,ename,sal from emp";
rs = stmt.executeQuery(sql);
//5、查询结果集
/*
boolean flag = rs.next();
//System.out.println(flag);//true.表示第一行有数据
if(flag){
//有数据,取数据
//getString()方法的特点是:不管数据库中的数据类型是什么,都以String的方式取出
String empno = rs.getString(1);//第一列是员工编号。注意JDBC中下标从1开始,不是从0开始
String ename = rs.getString(2);//第二列是员工名字
String sal = rs.getString(3);//第二列是薪资
System.out.println(empno+" | "+ename+" |"+sal);
}
*/
//查询结果集代码升级,使用循环
while(rs.next()){
/*
String empno = rs.getString(1);
String ename = rs.getString(2);
String sal = rs.getString(3);
*/
//建议参数写列名
//String empno = rs.getString("empno");//此处的参数是列名,不是数据库中的列名,是查询结果集中的列名。
/*
String empno = rs.getString("a");
String ename = rs.getString("ename");
String sal = rs.getString("sal");
*/
//除了使用getString类型,还可以使用getInt和getDouble
int empno = rs.getInt("a");
String ename = rs.getString("ename");
Double sal = rs.getDouble("sal");
System.out.println(empno+" | "+ename+" |"+(sal+100));
}
}catch(Exception e){
e.printStackTrace();
}finally{
//6、释放资源
//释放rs
if(rs != null){
try{
rs.close();
}catch(SQLException e){
e.printStackTrace();
}
}
//释放stmt
if(stmt != null){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
//释放conn
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*
JDBC编程六步,解决Mysql中34道作业题第2题
2、哪些人的薪水在部门的平均薪水之上
第一步:先找到部门的平均薪水
select deptno,avg(sal) from emp group by deptno;
第二步:将上表作为临时表和emp表联合查询,连接条件是e.deptno=d.deptno and sal>(平均薪资)
select
t.*,e.ename,e.sal
from
emp e
inner join
(select deptno,avg(sal) as avgsal from emp group by deptno) t
where
e.deptno = t.deptno and e.sal>t.avgsal
order by
deptno
asc;
+--------+-------------+-------+---------+
| deptno | avgsal | ename | sal |
+--------+-------------+-------+---------+
| 10 | 3208.333333 | KING | 5500.00 |
| 20 | 2392.500000 | FORD | 3300.00 |
| 20 | 2392.500000 | JONES | 3272.50 |
| 20 | 2392.500000 | SCOTT | 3300.00 |
| 30 | 1723.333333 | ALLEN | 1760.00 |
| 30 | 1723.333333 | BLAKE | 3135.00 |
+--------+-------------+-------+---------+
*/
import java.sql.*;
import java.util.*;
public class JDBCTest06{
public static void main(String[] args){
ResourceBundle bundle = ResourceBundle.getBundle("jdbc");
String driver = bundle.getString("driver");
String url = bundle.getString("url");
String username = bundle.getString("username");
String password = bundle.getString("password");
Connection conn = null;
Statement stmt = null;
try{
//1、注册驱动
Class.forName(driver);
//2、获取连接
conn = DriverManager.getConnection(url,username,password);
System.out.println(conn);
//3、获取数据库操作对象
stmt = conn.createStatement();
//4、执行SQL语句
String sql = "select t.*,e.ename,e.sal from emp e inner join (select deptno,avg(sal) as avgsal from emp group by deptno) t where e.deptno = t.deptno and e.sal>t.avgsal order by deptno asc";
//String sql = "insert into dept (deptno,dname,loc) values(11,'XIAOSHOU','WuWei')";
ResultSet rs = stmt.executeQuery(sql);
//int count = stmt.executeUpdate(sql);
//System.out.println(count == 1?"修改成功":"修改失败");
//5、查询结果集
while(rs.next()){
String deptno = rs.getString("deptno");
Double avgsal = rs.getDouble("avgsal");
String ename = rs.getString("ename");
Double sal = rs.getDouble("sal");
System.out.println(deptno+"|"+avgsal+"|"+ename+"|"+sal);
}
}catch(SQLException e){
e.printStackTrace();
}catch(ClassNotFoundException e){
e.printStackTrace();
}finally{
//6、释放资源
if(stmt != null){
try{
stmt.close();
}catch(SQLException e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
}catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
/*
代码成功运行,结果如下
10|3208.333333|KING|5500.0
20|2392.5|FORD|3300.0
20|2392.5|JONES|3272.5
20|2392.5|SCOTT|3300.0
30|1723.333333|ALLEN|1760.0
30|1723.333333|BLAKE|3135.0
*/
package com.bjpowernode.jdbc;
import javax.annotation.Resource;
import javax.xml.transform.Result;
import java.net.ConnectException;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.ResourceBundle;
import java.util.Scanner;
/**
* 实现用户登录任务;
* 1、需求:模拟用户登录功能的实现
* 2、提供输入口,用户输入用户名和密码后,连接数据库验证用户名和密码是否合法
* 3、数据的准备
*/
public class JDBCTest06 {
public static void main(String[] args) {
//初始化一个界面,定义一个方法实现,返回值是用户名和密码
Map<String,String> userLoginInfo = initUI();
//验证用户名和密码
Boolean loginSuccess = login(userLoginInfo);
//最后输出结果
System.out.println(loginSuccess ? "登录成功":"登录失败");
}
/**
* 用户登录
* @param userLoginInfo 用户登录名和密码
* @return 返回true表示登录成功,返回false表示登录失败
*/
private static boolean login(Map<String, String> userLoginInfo) {
//打标记的意识
boolean loginSuccess = false;
//单独定义变量拿到登录名和密码
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取数据库操作对象
stmt = conn.createStatement();
//4、执行SQL语句
String sql = "select * from t_user where loginName = '"+loginName+"' and loginPwd = '"+loginPwd+"'";
rs = stmt.executeQuery(sql);
//5、验证结果
if (rs.next()){//如果不为空,说明查到数据了
//登录成功
loginSuccess = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//6、释放资源
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面,
* @return 用户输入的登录名和密码等信息
*/
private static Map<String, String> initUI() {
//接受用户从键盘输入的用户名和密码
Scanner s = new Scanner(System.in);
System.out.print("请输入用户名:");
String loginName = s.nextLine();
System.out.print("请输入密码:");
String loginPwd = s.nextLine();
//将得到的用户名和密码添加到Map集合中
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
return userLoginInfo;
}
}
package com.bjpowernode.jdbc;
import java.sql.*;
import java.util.*;
/**
* 解决sql注入问题
*/
public class JDBCTest07 {
public static void main(String[] args) {
//初始化一个界面,定义一个方法实现,返回值是用户名和密码
Map<String,String> userLoginInfo = initUI();
//验证用户名和密码
Boolean loginSuccess = login(userLoginInfo);
//最后输出结果
System.out.println(loginSuccess ? "登录成功":"登录失败");
}
/**
* 用户登录
* @param userLoginInfo 用户登录名和密码
* @return 返回true表示登录成功,返回false表示登录失败
*/
private static boolean login(Map<String, String> userLoginInfo) {
//打标记的意识
boolean loginSuccess = false;
//单独定义变量拿到登录名和密码
String loginName = userLoginInfo.get("loginName");
String loginPwd = userLoginInfo.get("loginPwd");
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取预编译的数据库操作对象
//SQL语句的框架,其中一个?表示一个占位符,一个?会接收一个值,注意:占位符不要用括号括起来
String sql = "select * from t_user where loginName = ? and loginPwd = ?";
//程序执行到此处,会发送SQL语句的框子给DBMS,然后DBMS进行SQL语句的预编译
ps = conn.prepareStatement(sql);
//给占位符传值
ps.setString(1,loginName);
ps.setString(2,loginPwd);
//4、执行SQL语句
rs = ps.executeQuery();
//5、验证结果
if (rs.next()){//如果不为空,说明查到数据了
//登录成功
loginSuccess = true;
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//6、释放资源
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
return loginSuccess;
}
/**
* 初始化用户界面,
* @return 用户输入的登录名和密码等信息
*/
private static Map<String, String> initUI() {
//接受用户从键盘输入的用户名和密码
Scanner s = new Scanner(System.in);
System.out.print("请输入用户名:");
String loginName = s.nextLine();
System.out.print("请输入密码:");
String loginPwd = s.nextLine();
//将得到的用户名和密码添加到Map集合中
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("loginName",loginName);
userLoginInfo.put("loginPwd",loginPwd);
return userLoginInfo;
}
}
package com.bjpowernode.jdbc;
import java.sql.*;
import java.util.*;
public class JDBCTest08 {
// public static void main(String[] args) {
// //用户在控制台输入asc和desc。使用statement进行SQL注入
// Scanner scanner = new Scanner(System.in);
// System.out.println("请输入asc或desc,asc表示升序,desc表示降序:");
// System.out.println("请输入");
//
// String keyWords = scanner.nextLine();
//
//
// //执行SQL
// //JDBC编程六步
// Connection conn = null;
// //Statement stmt = null;
// PreparedStatement ps = null;
//
// ResultSet rs = null;
// try {
// //1、注册驱动
// Class.forName("com.mysql.jdbc.Driver");
// //2、获取连接
// conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
// //3、获取执行数据库操作的对象
// //stmt = conn.createStatement();
// String sql = "select ename,sal from emp order by sal ?";
// ps = conn.prepareStatement(sql);
// ps.setString(1,keyWords);
// //4、执行SQL语句
// rs = ps.executeQuery();
//
// //rs = stmt.executeQuery(sql);
// //5、查询结果集
// while (rs.next()){
// String ename = rs.getString("ename");
// int sal = rs.getInt("sal");
//
// System.out.println(ename+"|"+sal);
// }
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }finally {
// //6、释放资源
// if (rs != null){
// try {
// rs.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
// /*
// if (stmt != null){
// try {
// stmt.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
// */
// if (ps != null){
// try {
// ps.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
//
// if (conn != null){
// try {
// conn.close();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// }
// }
//
//
// }
public static void main(String[] args) {
//用户在控制台输入asc和desc。使用statement进行SQL注入
Scanner scanner = new Scanner(System.in);
System.out.println("请输入asc或desc,asc表示升序,desc表示降序:");
System.out.println("请输入");
String keyWords = scanner.nextLine();
//执行SQL
//JDBC编程六步
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取执行数据库操作的对象
stmt = conn.createStatement();
//4、执行SQL语句
String sql = "select ename,sal from emp order by sal "+keyWords;
rs = stmt.executeQuery(sql);
//rs = stmt.executeQuery(sql);
//5、查询结果集
while (rs.next()){
String ename = rs.getString("ename");
int sal = rs.getInt("sal");
System.out.println(ename+"|"+sal);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//6、释放资源
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
package com.bjpowernode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCTest09 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取预编译的数据库操作对象
//增加
/*
String sql = "insert into dept(deptno,dname,loc) values(?,?,?)";
ps = conn.prepareStatement(sql);
//给占位符赋值
ps.setInt(1,60);
ps.setString(2,"销售部");
ps.setString(3,"上海");
*/
//修改
/*
String sql = "update dept set dname=?,loc=? where deptno=?";
ps = conn.prepareStatement(sql);
//给占位符赋值
ps.setString(1,"研发部");
ps.setString(2,"深圳");
ps.setInt(3,60);
*/
//删除
String sql = "delete from dept where deptno=?";
ps = conn.prepareStatement(sql);
//给占位符赋值
ps.setInt(1,11);
//4、执行sql语句
int count = ps.executeUpdate();
System.out.println("修改的记录条数是:"+count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//6、释放资源
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
package com.bjpowernode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCTest10 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//3、获取预编译的数据库操作对象
String sql = "update dept set dname = ? where deptno = ?";
ps = conn.prepareStatement(sql);
//第一次给占位符赋值
ps.setString(1,"M部门");
ps.setInt(2,20);
//4、执行sql语句
int count = ps.executeUpdate();
System.out.println("修改的记录条数是:"+count);
//第二次给占位符传值`
ps.setString(1,"N部门");
ps.setInt(2,30);
//4、执行sql语句
count = ps.executeUpdate();
System.out.println("修改的记录条数是:"+count);
} catch (Exception e) {
e.printStackTrace();
}finally {
//6、释放资源
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
- 重点:
conn.setAutoCommit(false)
conn.commit()
conn.rollback()
package com.bjpowernode.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
* sql脚本:
* drop table if exists t_act
* create table t_act(
* actno int
* balance double(7,2)//7表示有效数字的个数,2表示小数位
* );
* insert into t_act(actno,balance) values(111,20000);
* insert into t_act(actno,balance) values(222,0);
* =======
*
* 实现账户转账
*
* 重点:
* conn.setAutoCommit(false)
* conn.commit()
* conn.rollback()
*
*
* */
public class JDBCTest11 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//1、注册驱动
Class.forName("com.mysql.jdbc.Driver");
//2、获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
//将自动提交机制修改为手动提交
conn.setAutoCommit(false);//开启事务
//3、获取预编译的数据库操作对象
String sql = "update t_act set balance = ? where actno = ?";
ps = conn.prepareStatement(sql);
//给占位符赋值,将第一个账户的余额减少为10000
ps.setDouble(1,10000);
ps.setInt(2,111);
int count = ps.executeUpdate();
//让这里出现异常,使代码直接进入catch中。会导致下面代码不执行,而JDBC的自动提交机制将上面的修改提交了。所以要将自动提交机制关闭。
// String str = null;
// str.length();
//
//将第二个账户的余额增加为10000
ps.setDouble(1,10000);
ps.setInt(2,222);
count += ps.executeUpdate();
//4、执行sql语句
ps.executeUpdate();
//5、查询结果集
System.out.println(count == 2 ? "转账成功":"转账失败");
//只要程序到达这里,说明事务结束,手动提交
conn.commit();//提交事务
} catch (Exception e) {
try {
conn.rollback();//回滚事务
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
}finally {
//6、释放资源
if (ps != null){
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
package com.bjpowernode.jdbc.util;
import java.sql.*;
/**
* @Author:马仲杰
* @Date 2021/4/14
*
* JDBC工具类,简化JDBC编程
*
*
**/
public class DBUtil {
/**
* 工具类中的构造方法一般是私有的
* 因为工具类中的方法都是静态的,不需要new对象,直接采用类名调用
*
*/
/*
静态代码块在类加载时执行,且只执行一次,在这里注册驱动。
*/
private DBUtil(){}
static {
try {
//注册驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 获取数据库连接对象
* @return 连接对象
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/bjpowernode","root","333");
}
public static void close(Connection conn, Statement stmt, ResultSet rs){
if (rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
package com.bjpowernode.jdbc;
import com.bjpowernode.jdbc.util.DBUtil;
import java.sql.*;
/**
* @Author:马仲杰
* @Date 2021/4/14
*
*
* 任务1:测试DBUtil
* 任务2:实现模糊查询
**/
public class JDBCTest12 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//注册驱动
try {
//获取链接
conn = DBUtil.getConnection();
//获取预编译的操作对象
String sql = "select ename from emp where ename like ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"_A%");
//执行代码
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}finally {
//释放资源
DBUtil.close(conn,ps,rs);//注意顺序
}
}
}
package com.bjpowernode.jdbc;
import com.bjpowernode.jdbc.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/**
* @Author:马仲杰
* @Date 2021/4/15
* 这个事务开启一个事务专门进行查询,并且使用行级锁【悲观锁】
**/
public class JDBCTest13 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
//获取连接
conn = DBUtil.getConnection();
//开启事务
conn.setAutoCommit(false);
//获取预编译的数据库的执行对象
String sql = "select ename,job,sal from emp where job = ? for update";
ps = conn.prepareStatement(sql);
ps.setString(1,"MANAGER");
//执行SQL语句
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename")+"|"+
rs.getString("job")+"|"+rs.getDouble("sal"));
}
//提交事务【事务结束】
conn.commit();
} catch (SQLException throwables) {
//回滚事务【事务结束】
if (conn != null){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
//关闭资源
DBUtil.close(conn,ps,rs);
}
}
}
package com.bjpowernode.jdbc;
import com.bjpowernode.jdbc.util.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @Author:马仲杰
* @Date 2021/4/15
*这个程序负责修改被锁住的记录
**/
public class JDBCTest14 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
//获取连接
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
//获取预编译的操作对象
String sql = "update emp set sal = sal * 1.1 where job = ?";
ps = conn.prepareStatement(sql);
ps.setString(1,"MANAGER");
//执行sql语句
int count = ps.executeUpdate();
System.out.println(count);
conn.commit();
} catch (SQLException throwables) {
if (conn != null){
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
throwables.printStackTrace();
}finally {
//释放资源
DBUtil.close(conn,ps,null);
}
}
}
====================================================================================================JDBC完结2021.4.15
复习第一次:2021.5.12