文章目录
JDBC
1、JDBC是什么?
Java DataBase Connectivity(Java语言连接数据库)
2、JDBC的本质是什么?
JDBC是SUN公司制定的一套接口(interface)
java.sql.*; (这个软件包下有很多接口。)
接口都有调用者和实现者。
面向接口调用、面向接口写实现类,这都属于面向接口编程。
为什么要面向接口编程?
解耦合:降低程序的耦合度,提高程序的扩展力。
多态机制就是非常典型的:面向抽象编程。(不要面向具体编程)
建议:
Animal a = new Cat();
Animal a = new Dog();
// 喂养的方法
public void feed(Animal a){
// 面向父类型编程。
}
不建议:
Dog d = new Dog();
Cat c = new Cat();
思考:为什么SUN制定一套JDBC接口呢?
因为每一个数据库的底层实现原理都不一样。
Oracle数据库有自己的原理。
MySQL数据库也有自己的原理。
MS SqlServer数据库也有自己的原理。
…
每一个数据库产品都有自己独特的实现原理。
JDBC的本质到底是什么?
一套接口。
3、JDBC开发前的准备工作
先从官网下载对应的驱动jar包,然后将其配置到环境变量classpath当中。
classpath=.;D:\course\06-JDBC\resources\MySql Connector Java 5.1.23\mysql-connector-java-5.1.23-bin.jar
以上的配置是针对于文本编辑器的方式开发,使用IDEA工具的时候,不需要配置以上的环境变量。
IDEA有自己的配置方式。
4、JDBC编程主要步骤
-
第一步:注册驱动(作用:告诉Java程序,即将要连接的是哪个品牌的数据库)
-
第二步:获取连接(表示JVM的进程和数据库进程之间的通道打开了,这属于进程之间的通信,重量级的,使用完之后一定要关闭通道。)
-
第三步:获取数据库操作对象(专门执行sql语句的对象)
-
第四步:执行SQL语句(DQL DML…)
-
第五步:处理查询结果集(只有当第四步执行的是select语句的时候,才有这第五步处理查询结果集。)
-
第六步:释放资源(使用完资源之后一定要关闭资源。Java和数据库属于进程间的通信,开启之后一定要关闭。)
1.基本流程
import java.sql.*;
public class JDBCTest01 {
public static void main(String[] args) {
Connection conn = null;
Statement stmt = null;
try{
// 1、注册驱动
Driver driver = new com.mysql.jdbc.Driver(); //多态,父类型引用指向子类型对象
DriverManager.registerDriver(driver);
// 2、获取连接
/*
url包括哪几部分:
协议
IP
Port
资源名
eg:http://180.101.49.11:80/index.html
http:// 通信协议
180.101.49.11 IP地址
80 端口号
index.html 资源名
*/
// static Connection getConnection(String url, String user, String password)
String url = "jdbc:mysql://127.0.0.1:3306/mydatabase";
String user = "root";
String password = "146";
conn = DriverManager.getConnection(url,user,password);
System.out.println("数据库连接对象" + conn); //数据库连接对象com.mysql.jdbc.JDBC4Connection@1ae369b7
// 3、获取数据库操作对象
// Statement createStatement() 创建一个 Statement 对象来将 SQL 语句发送到数据库。
stmt = conn.createStatement();
// 4、执行sql语句
// int executeUpdate(String sql)
// 专门执行DML语句
// 返回值是“影响数据库中的记录条数”
int count = stmt.executeUpdate("update dept set dname = '销售部',loc = '合肥' where deptno = 20;");
System.out.println(count == 1 ? "保存成功":"保存失败");
// 5、处理查询结果集
} 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();
}
}
}
}
}
2.JDBC完成Delete
/*
JDBC完成Delete
*/
import java.sql.*;
public class JDBCTest02 {
public static void main(String[] args) {
// 1、注册驱动
// 2、获取连接
// 3、获取数据库操作对象
// 4、执行sql语句
// 5、获取查询结果集
// 6、释放资源
Connection conn = null;
Statement stmt = null;
try {
Driver driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
String url = "jdbc:mysql://127.0.0.1:3306/mydatabase";
String user = "root";
String password = "146";
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
int count = stmt.executeUpdate("delete from dept where deptno = 50");
System.out.println(count == 1? "删除成功":"删除失败");
} catch(SQLException e){
e.printStackTrace();
} finally {
if(conn != null) {
try {
conn.close();
} catch(SQLException e){
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
3.注册驱动的另一种方式
/*
注册驱动的另一种方式
*/
import java.sql.*;
public class JDBCTest03 {
public static void main(String[] args) {
try{
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
System.out.println(conn);
} catch(SQLException e){
e.printStackTrace();
} catch(ClassNotFoundException e){
e.printStackTrace();
}
}
}
4.使用资源绑定器 ResourceBundle
/*
使用资源绑定器
*/
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 user = bundle.getString("user");
String password = bundle.getString("password");
Connection conn = null;
Statement stmt = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
int count = stmt.executeUpdate("insert into dept(deptno,dname,loc) values(50,'人事部','北京');");
System.out.println(count == 1? "保存成功":"保存失败");
} catch(SQLException e){
e.printStackTrace();
} catch(ClassNotFoundException e) {
e.printStackTrace();
} finally {
if(conn != null) {
try {
conn.close();
} catch(SQLException e){
e.printStackTrace();
}
}
if(stmt != null) {
try {
stmt.close();
} catch(SQLException e){
e.printStackTrace();
}
}
}
}
}
5.执行DQL语句
/*
执行DQL语句
*/
import java.sql.*;
import java.util.*;
public class JDBCTest05 {
public static void main(String[] args) {
// 1、注册驱动
// 2、建立连接
// 3、获取数据库操作对象
// 4、执行sql语句
// 5、获取查询结果集
// 6、释放资源
Connection conn = null;
Statement stmt = null;
ResultSet rs = null; // 查询返回的是结果 其他的 增删改 都是返回改动的行数
try{
ResourceBundle rb = ResourceBundle.getBundle("jdbc");
String driver = rb.getString("driver");
String url = rb.getString("url");
String user = rb.getString("user");
String password = rb.getString("password");
Class.forName(driver);
conn = DriverManager.getConnection(url,user,password);
stmt = conn.createStatement();
rs = stmt.executeQuery("select empno,ename,sal from emp");
while(rs.next()){
/*
String empno = rs.getString(1);
String ename = rs.getString(2);
String sal = rs.getString(3);
System.out.println(empno + "," + ename + "," + sal);
*/
/*
// 按下标取出,程序不健壮
String empno = rs.getString("empno");
String ename = rs.getString("ename");
String sal = rs.getString("sal");
System.out.println(empno + "," + ename + "," + sal);
*/
/*
// 以指定的格式取出
int empno = rs.getInt(1);
String ename = rs.getString(2);
double sal = rs.getDouble(3);
System.out.println(empno + "," + ename + "," + (sal + 100));
*/
int empno = rs.getInt("empno");
String ename = rs.getString("ename");
double sal = rs.getDouble("sal");
System.out.println(empno + "," + ename + "," + (sal + 200));
}
} catch(Exception e){
e.printStackTrace();
}finally{
if(rs != null){
try{
rs.close();
} catch (Exception e){
e.printStackTrace();
}
}
if(stmt != null){
try{
stmt.close();
} catch (Exception e){
e.printStackTrace();
}
}
if(conn != null){
try{
conn.close();
} catch (Exception e){
e.printStackTrace();
}
}
}
}
}
5.模拟实现用户登录功能
package bj.java.jdbc;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
/*
模拟实现用户登录功能
*/
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;
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/mydatabase","root","146");
// 3、获取数据库操作对象
stmt = conn.createStatement();
// 4、执行sql语句
String sql = "select * from t_user where userName = '"+ userLoginInfo.get("userName")+ "' and userPassword = '" + userLoginInfo.get("userPassword")+ "'";
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 userName = s.nextLine();
System.out.print("请输入密码:");
String userPassword = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("userName",userName);
userLoginInfo.put("userPassword",userPassword);
return userLoginInfo;
}
}
6.预编译解决SQL注入问题
package bj.java.jdbc;
import java.sql.*;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
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;
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/mydatabase","root","146");
// 3、获取预编译的数据库操作对象
// sql语句的框架中,一个?,表示一个占位符,一个?将来接收一个值。注意:?不要用单引号括起来
String sql = "select * from t_user where userName = ? and userPassword = ?";
// 程序执行到此处,会发送sql语句框架给DBMS,DBMS对sql语句框架进行预编译。
ps = conn.prepareStatement(sql);
// 给占位符?传值,第一个?的下标是1,第二个?的下标是2(JDBC中下标都从1开始)
ps.setString(1,userLoginInfo.get("userName"));
ps.setString(2,userLoginInfo.get("userPassword"));
// 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 userName = s.nextLine();
System.out.print("请输入密码:");
String userPassword = s.nextLine();
Map<String,String> userLoginInfo = new HashMap<>();
userLoginInfo.put("userName",userName);
userLoginInfo.put("userPassword",userPassword);
return userLoginInfo;
}
}
7.在需要sql注入时statement用途
package bj.java.jdbc;
import java.sql.*;
import java.util.Scanner;
public class JDBCTest08 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或者asc");
String keyWords = s.nextLine();
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
String sql = "select ename from emp order by ename ?";
ps = conn.prepareStatement(sql);
ps.setString(1,keyWords);
rs = ps.executeQuery();
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (ps != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
package bj.java.jdbc;
import java.sql.*;
import java.util.Scanner;
public class JDBCTest09 {
public static void main(String[] args) {
Scanner s = new Scanner(System.in);
System.out.println("请输入desc或者asc");
String keyWords = s.nextLine();
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
stmt = conn.createStatement();
String sql = "select ename from emp order by ename " + keyWords;
rs = stmt.executeQuery(sql);
while(rs.next()){
System.out.println(rs.getString("ename"));
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (stmt != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
8.使用PreparedStatement完成insert、update、delete
package bj.java.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/*
使用PreparedStatement完成insert、update、delete
*/
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/mydatabase","root","146");
// 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,60);
// 4、执行sql语句
int count = ps.executeUpdate();
System.out.println(count == 1? "修改成功" : "修改失败");
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException throwables) {
throwables.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();
}
}
}
}
}
9.JDBC事务 自动提交演示
package bj.java.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCTest11 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
// 获取预编译的数据库操作对象
String sql = "update t_act set balance = ? where actno = ? ";
ps = conn.prepareStatement(sql);
ps.setInt(1,10000);
ps.setDouble(2,111);
// 执行sql语句
int count = ps.executeUpdate();
//程序执行期间出现错误
String s = null;
s.toString();
ps.setInt(1,10000);
ps.setDouble(2,222);
count += ps.executeUpdate();
System.out.println(count == 2 ? "转账成功" : "转账失败");
} catch (Exception e) {
e.printStackTrace();
} finally {
// 释放资源
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
package bj.java.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCTest12 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
// 注册驱动
Class.forName("com.mysql.jdbc.Driver");
// 获取连接
conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
// 将自动提交改为手动提交
conn.setAutoCommit(false);
// 获取预编译的数据库操作对象
String sql = "update t_act set balance = ? where actno = ? ";
ps = conn.prepareStatement(sql);
ps.setInt(1,10000);
ps.setDouble(2,111);
// 执行sql语句
int count = ps.executeUpdate();
/*String s = null;
s.toString();*/
ps.setInt(1,10000);
ps.setDouble(2,222);
count += ps.executeUpdate();
System.out.println(count == 2 ? "转账成功" : "转账失败");
// 程序能执行到此处,说明没有异常,事务结束,手动提交数据
conn.commit();
} catch (Exception e) {
// 遇到异常,回滚
if (conn != null) {
try {
conn.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
e.printStackTrace();
} finally {
// 释放资源
if (ps != null) {
try {
ps.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}
}
10.JDBC工具类,简化JDBC编程
package bj.java.jdbc.DBUtil;
import java.sql.*;
/*
JDBC工具类,简化JDBC编程
*/
public class DBUtil {
/**
* 工具类中的构造方法是私有的 防止造对象
* 因为工具类中的方法都是静态的,直接通过类名去调即可。
*/
private DBUtil(){}
/**
* 静态代码块,类加载的时候执行
* 把注册驱动程序的代码放在静态代码块中,避免多次获取连接对象时重复调用
*/
static {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection("jdbc:mysql://localhost:3306/mydatabase","root","146");
}
public static void close(Connection conn, Statement ps, ResultSet rs){
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();
}
}
}
}
package bj.java.jdbc;
import bj.java.jdbc.DBUtil.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
1、测试DBUtil工具类
2、模糊查询
*/
public class JDBCTest13 {
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();
}
}
}
11.行级锁/悲观锁
package bj.java.jdbc;
import bj.java.jdbc.DBUtil.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
/*
行级锁/悲观锁 并发执行是串行的 会卡住等待
*/
public class JDBCTest14 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtil.getConnection();
// 开启事务
conn.setAutoCommit(false);
ps = conn.prepareStatement("select ename,job,sal from emp where job = ? for update ");
ps.setString(1,"MANAGER");
rs = ps.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("ename") + "," + rs.getString("job") + "," + rs.getString("sal"));
}
// 提交事务(事务结束)
conn.commit();
} catch (SQLException throwables) {
// 回滚事务(事务结束)
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
} finally {
DBUtil.close(conn,ps,rs);
}
}
}
package bj.java.jdbc;
import bj.java.jdbc.DBUtil.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class JDBCTest15 {
public static void main(String[] args) {
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtil.getConnection();
conn.setAutoCommit(false);
ps = conn.prepareStatement("update emp set sal = sal * 1.1 where job = ?");
ps.setString(1,"MANAGER");
int count = ps.executeUpdate();
System.out.println(count);
conn.commit();
} catch (SQLException throwables) {
try {
conn.rollback();
} catch (SQLException e) {
e.printStackTrace();
}
throwables.printStackTrace();
} finally {
DBUtil.close(conn,ps,null);
}
}
}
学习自powernode JDBC