JDBC
概述
-
JDBC为访问不同的数据库提供了统一的接口,为使用者屏蔽了细节问题
-
java程序员使用JDBC,可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作
-
JDBC基本原理图
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-RCcVgjme-1665405431077)(C:\Users\爱吃橙子7\Desktop\图片.png)]
JDBC入门
JDBC第一个程序
package com.xyf.jdbc;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* @program :这是第一个jdbc程序 完成简单的操作
* @Author :许逸帆
* @Date :2022/2/10 23:38
*/
public class Jdbc01 {
public static void main(String[] args) throws SQLException {
//1.注册驱动
Driver driver = new Driver();
//2.得到连接
//(1)jdbc:mysql:// 规定好表示协议,通过jdbc的方法连接mysql
//(2)localhos 主机,可以是ip地址
//(3)3306 表示mysql监听的端口
//(4)xyf_db02 表示想要连接的数据库
//(5)mysql的连接本质就是前面学过的socket连接
String url = "jdbc:mysql://localhost:3306/xyf_db02";
//将用户名和密码放入到Properties对象中
Properties properties = new Properties();
properties.setProperty("user","root");//用户名
properties.setProperty("password","123456");//密码
Connection connect = driver.connect(url, properties);
//3.执行sql
String sql = "insert into actor values(null,'刘德华','男','1961-9-27','110')";
// String sql = "update actor set name='周星驰' where id=1";
// String sql = "delete actor from actor where id=1";
//用于执行静态SQl语句并返回其生成的结果的对象
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql);
System.out.println(rows>0?"成功":"失败");
//4.关闭连接资源
statement.close();
connect.close();
}
}
获取数据库连接的5种方式
方式1
会直接使用com.mysql.jdbc.Driver(),属于静态加载,灵活性差,依赖强
//会直接使用com.mysql.jdbc.Driver(),属于静态加载,灵活性差,依赖强
Driver driver = new com.mysql.jdbc.Driver();
String url = "jdbc:mysql://localhost:3306/jdbc_db";
Properties info = new Properties();
info.setProperty("user","root");
info.setProperty("password","hsp");
Connection conn = driver.connect(url,info);
方式2
使用反射进行driver驱动的动态加载 灵活性较强
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/jdbc_db";
info.setProperty("user","root");
info.setProperty("password","hsp");
Connection conn = driver.connect(url,info);
方式3
使用DriverManager替换Driver进行统一管理
//使用DriverManager替换Driver
Class clazz = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver)clazz.newInstance();
String url = "jdbc:mysql://localhost:3306/jdbc_db";
String user = "root";
String password = "hsp";
DriverManager.registerDriver(driver);
Connection conn = DriverManager.getConnection(url,user,password);
方法4
使用Class.forName 自动完成注册驱动,简化代码
这种方式获取链接使使用最多的,推荐使用
Class.forName("com.mysql.jdbc.Driver");
String url = "jdbc:mysql://localhost:3306/jdbc_db";
String user = "root";
String password = "123";
Connection conn = DriverManager.getConnection(url,user,password);
提示:
- mysql驱动5.1.6可以无需Class.forName(“com.mysql.jdbc.Driver”);
- 从jdk1.5以后使用了jdbc4,不再需要显示调用class.forName()注册驱动而是自动调用驱动jar包下META-INF\services\jaca.sql.Driver文本中的类名去注册
- 建议还是写上Class.forName(“com.mysql.jdbc.Driver”); 更加明确
方法5
在方式4的基础上改进,使用配置文件,连接数据库更加灵活
//通过 Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
//获取相关的值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
String url = properties.getProperty("url");
Class.forName(driver);//建议写上
Connection connection = DriverManager.getConnection(url, user, password);
配置文件
user=root
password=root
url=jdbc:mysql://localhost:3306/xyf_db02?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
提交sql语句
1.增、删、修改操作
返回值为改动的数据条数
Statement statement = connection.createStatement();
int rows = statement.executeUpdate(“sql语句”);
2.查询操作
返回值为数据集ResultSet
statement.executeQuery("sql语句");
ResultSet[结果集]
- 表示数据库结果集的数据表,通常通过执行查询数据库的语句生成
- ResultSet对象保持一个光标指向其当前的数据行。最初,光标位于第一行之前
- next方法将光标移动到下一行,并且由于是在ResultSet对象中没有更多行使返回false,因此可以在while循环中使用循环来遍历结果
package com.xyf.jdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Date;
import java.util.Properties;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/13 10:47
*/
public class ResultSet_{
public static void main(String[] args) throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
//1.注册驱动
Class.forName(driver);
//2.得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3.得到Statement
Statement statement = connection.createStatement();
//4.组织sql语句
String sql = "select id,name,sex,borndate from actor";
ResultSet resultSet = statement.executeQuery(sql);
//5.使用while取出数据
while(resultSet.next()){
int id = resultSet.getInt(1);
String name = resultSet.getString(2);
String sex = resultSet.getString(3);
Date borndate = resultSet.getDate(4);
System.out.println(id + "\t" + name + "\t" + sex + "\t" + borndate);
}
//6.关闭连接
statement.close();
connection.close();
resultSet.close();
}
}
Statement
- Statement对象用于执行静态SQL语句并返回其生成的结果的对
- 在连接建立后,需要对数据库进行访问,执行命令或者是SQL语句,可以通过Statement[存在SQL注入]、PreparedStatement[预处理]、CallableStatement[存储处理]。
- Statement对象执行SQL语句,存在SQL注入风险
- SQl注入是利用某些系统没有对用户输入的数据进行充分的检查,而在用户输入数据中注入非法的SQL语句段或命令,恶意攻击数据库。
- 要方法SQL注入,只要用PreparedStatement(从Statement扩展而来)取代Statement就可以了。
PreparedStatement
- PreparedStatement执行的SQL语句中的参数用问号(?)来表示,调用PreparedStatement对象的setXxx()方法来设置这些参数。setXxx()方法右两个参数,第一个参数是要设置的SQL语句中的参数的索引(从1开始),第二个是设置的SQl语句中的参数的值。
- 调用executeQuery(),返回ResultSet对象
- 调用executeUpdate(),执行更新,包括增、删、修改。
package com.xyf.jdbc;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
import java.util.Scanner;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/13 13:32
*/
public class PerparedStatement {
public static void main(String[] args) throws Exception{
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
//获取用户名和密码
Scanner scanner = new Scanner(System.in);
System.out.print("请输入用户名:");
String admin_name = scanner.nextLine();
System.out.print("请输入密码:");
String admin_pwd = scanner.nextLine();
//1.注册驱动
Class.forName(driver);
//2.得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3.1得到Statement
String sql = "select name,pwd from admin where name = ? and pwd = ?";
//3.2preparedStatement 对象实现 PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3 给?赋值
preparedStatement.setString(1,admin_name);
preparedStatement.setString(2,admin_pwd);
ResultSet resultSet = preparedStatement.executeQuery();
if(resultSet.next()){
System.out.println("登录成功!");
}else {
System.out.println("登录失败");
}
//6.关闭连接
preparedStatement.close();
connection.close();
resultSet.close();
}
}
封装JDBCUtils【关闭、得到连接】
工具类 JDBCUtils.java
package com.xyf.jdbc.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
/**
* @program :这是一个工具类 完成mysql的连接和关闭资源
* @Author :许逸帆
* @Date :2022/2/15 14:00
*/
public class JDBCUtils {
//定义相关的属性(4个),因为只需要一份,因此做成静态的
private static String user;//用户名
private static String password;//密码
private static String url;//url
private static String driver;//驱动名
//在static代码块中初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src\\mysql.properties"));
//读取相关的属性值
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
driver = properties.getProperty("driver");
} catch (IOException e) {
//在实际开发中,我们可以这样处理
//1.将编译异常转成运行异常
//2.这时调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便。
throw new RuntimeException(e);
}
}
//连接数据库 返回一个connection、
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,user,password);
} catch (SQLException e) {
//在实际开发中,我们可以这样处理
//1.将编译异常转成运行异常
//2.这时调用者,可以选择捕获该异常,也可以选择默认处理该异常,比较方便。
throw new RuntimeException(e);
}
}
//关闭相关资源
/*
1.ResultSet 结果集
2.Statement 或者 PreparedStatement
3.Connection
*/
public static void close(ResultSet set, Statement statement,Connection connection){
//判断是否为null
try {
if(set != null){
set.close();
}
if(statement != null){
statement.close();
}
if(connection != null){
connection.close();
}
} catch (SQLException e) {
//将编译异常转成运行异常抛出
throw new RuntimeException(e);
}
}
}
实际使用使用工具类 JDBCUtils.java
package com.xyf.jdbc.utils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @program :演示如何使用JDBCUtils工具类,完成dml和select
* @Author :许逸帆
* @Date :2022/2/15 19:20
*/
public class JDBCUtils_use {
@Test
public void testDML() {//insert,update,delete
//1.得到连接
Connection connection = null;
//2.组织sql语句
String sql = "update actor set name = ? where name = ?";
int row = 0;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,"李小龙");
preparedStatement.setString(2,"周润发");
row = preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
if(row > 0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
JDBCUtils.close(null,null,connection);
}
}
事务
- JDBC程序中当第一个Connection对象创建时,默认情况下是自动提交事务;每次执行一个SQL语句时,如果执行成功,就会向数据库自动提交,而不能回滚。
- JDBC程序中为了让多个SQL语句作为一个整体执行,需要使用事务
- 调用Connection的setAutoCommit(false)可以去校自动提交事务
- 在所有的SQL语句都成功执行后,调用Connection的commit();方法提交事务
- 在其中某个操作失败或出现异常时,调用Connection的rollback();方法回滚事务
通过事务解决转账问题
package com.xyf.jdbc;
import com.xyf.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @program :演示JDBC中如何使用事务
* @Author :许逸帆
* @Date :2022/2/17 0:05
*/
public class transaction_ {
//事务来解决转账问题
@Test
public void useTrancation(){
//1.得到连接
Connection connection = null;
//2.组织sql语句
String sql = "update account set balance = balance-100 where id = 1";
String sql2 = "update account set balance = balance+100 where id = 2";
int row = 0;
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtils.getConnection();
//将connection 设置为不自动提交
connection.setAutoCommit(false);//相当于开启了事务
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();//执行第一条语句
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();//执行第二条语句
//这里提交事务
connection.commit();
} catch (Exception e) {
//这里我们可以进行回滚,即撤销执行的SQL
//默认回滚到事务开始的状态
System.out.println("执行发生了异常,撤销执行的sql");
try {
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null,preparedStatement,connection);
}
if(row > 0){
System.out.println("修改成功");
}else{
System.out.println("修改失败");
}
JDBCUtils.close(null,null,connection);
}
}
批处理
-
当需要成批插入或者更新记录时,可以采用java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理,通常情况下比单独提交处理更有效率
-
JDBC的批量处理语句包括下面方法:
addBatch():添加需要批量处理的SQL语句或参数
executeBatch():执行批量处理语句
clearBatch():清空批处理的语句
-
JDBC连接Mysql时,如果需要使用批处理功能,请在url中加参数***?rewriteBatchedStatements=true***
-
批处理往往和PreparedStatement一起搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高
package com.xyf.jdbc;
import com.xyf.jdbc.utils.JDBCUtils;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
/**
* @program :演示使用批处理向admin2表中添加5000条数据
* @Author :许逸帆
* @Date :2022/2/17 9:31
*/
public class Batch_ {
@Test
public void testBatch() throws SQLException {
//1.获取连接
Connection connection = JDBCUtils.getConnection();
//2.执行插入
PreparedStatement statement = connection.prepareStatement("insert into admin2 values (null,?,?)");
long start = System.currentTimeMillis();
for (int i = 1; i < 5000; i++) {
statement.setString(1,"tom"+i);
statement.setString(2,(int)(Math.random()*100000000)+"");
statement.addBatch();//添加sql语句到处理包中
if((i+1) % 1000 == 0){
statement.executeBatch();//执行批处理包中的sql语句
statement.clearBatch();//清空处理包中的sql语句
}
}
long end = System.currentTimeMillis();
System.out.println("耗时:" + (end - start));
}
}
实例
①jdbc案例
要求
- 创建news表
- 使用jdbc添加5条数据
- 修改id=1的记录,将content改成一个新的消息
- 删除id=3的记录
package com.xyf.jdbc;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/11 23:39
*/
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* 1.创建news表
* 2.使用jdbc添加五条数据
* 3.修改id=1的记录,将content改成 一个新的消息
* 4.删除id=3的记录
*/
public class Exercise01 {
public static void main(String[] args) throws SQLException, ClassNotFoundException, IOException {
connect();
}
public static void connect() throws ClassNotFoundException, SQLException, IOException {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\mysql.properties"));
String url = properties.getProperty("url");
String root = properties.getProperty("root");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, root, password);
//创建表news
String create = "create table news(id int primary key auto_increment,content varchar(100))";
//加入五条数据
String insert = "insert into news values(null,'1'),(null,'2'),(null,'3'),(null,'4'),(null,'5')";
//修改id=1的记录,将content改成 一个新的消息
String update = "update news set content='一个新的消息' where id = 1";
//删除id=3的记录
String delete = "delete news from news where id = 3";
Statement statement = connection.createStatement();
int rows = statement.executeUpdate(insert);
System.out.println(rows>0?"成功":"失败");
}
}
数据库连接池
传统获取Connection问题分析
- 传统的JDBC数据库连接使用DriverManager来获取,每次向数据库建立连接的时候都要讲Connection加载到内存中,在验证IP地址、用户名和密码(0.5s-1s时间)。需要数据库连接的时候,就向数据库要求一个,频繁的进行数据库连接操作将占用很多的系统资源,容易造成服务器崩溃。
- 每一次数据库连接,使用完后都得断开,如果程序出现异常而未能关闭,将导致数据库内存泄漏,最终将导致重启数据库。
- 传统获取连接的方式,不能控制创建的连接数量,如果连接过多,也可能导致内存泄漏,MySQL崩溃。
- 解决传统开发中的数据库连接问题,可以采用数据库连接池技术。
数据库连接池种类
- JDBC的数据库连接池使用javax.sql.DataSource来表示,DataSource只是一个接口,该接口通常由第三方提供实现[提供jar文件]
- C3P0数据库连接池,速度相对较慢,稳定性不错(hibernate,spring)
- DBCP数据库连接池,速度相对C3P0较快,但不稳定
- Proxool数据库连接池,有监控连接池状态的功能,稳定性较C3P0差一点
- BoneCP数据库连接池,速度快
- **Druid(德鲁伊)**是阿里提供的数据库连接池,集DBCP、C3P0、Proxool优点于一身的数据库连接池
Druid(德鲁伊)应用实例
package com.xyf.jdbc;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.jupiter.api.Test;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/20 10:19
*/
public class Druid_ {
@Test
public void testDruid() throws Exception {
//1.加入Druid的jar包
//2.加入 配置文件 druid.properties ,将文件拷贝到项目的src目录
//3.创建一个properties对象 用来读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
//4.创建一个指定参数的数据库连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
System.out.println("Successfully connectied!");
connection.close();
}
}
使用Druid实现JDBCUtils工具类
工具类JDBCUtilsByDruid
package com.xyf.jdbc.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/20 10:37
*/
public class JDBCUtilsByDruid {
static DataSource ds;
static{
try {
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
public static void close(ResultSet set, Statement statement, Connection connection){
try {
if(set!=null){
set.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
使用工具类JDBCUtilsByDruid
package com.xyf.jdbc.utils;
import com.xyf.jdbc.Actor;
import org.junit.jupiter.api.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Date;
/**
* @program :
* @Author :许逸帆
* @Date :2022/2/20 11:05
*/
public class JDBCUtilsByDruid_use {
@Test
public void testSelect() {//insert,update,delete
//1.得到连接
Connection connection = null;
ResultSet set = null;
//2.组织sql语句
String sql = "select * from actor where id >= ?";
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtilsByDruid.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
set = preparedStatement.executeQuery();
while(set.next()){
int id = set.getInt("id");
String name = set.getString("name");
String sex = set.getString("sex");
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
System.out.println("id = " + id + "\tname = " + name + "\tsex = " + sex + "\tborndate = " + borndate + "\tphone = " + phone);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(null,preparedStatement,connection);
}
JDBCUtils.close(null,null,connection);
}
//使用土方法来解决ResultSet封装到ArrayList集合中
@Test
public ArrayList<Actor> testSelectToArrayList() {//insert,update,delete
//1.得到连接
Connection connection = null;
ResultSet set = null;
ArrayList<Actor> list = new ArrayList<>();//创建ArrayList对象,存放actor对象
//2.组织sql语句
String sql = "select * from actor where id >= ?";
PreparedStatement preparedStatement = null;
try {
connection = JDBCUtilsByDruid.getConnection();
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,1);
set = preparedStatement.executeQuery();
while(set.next()){
int id = set.getInt("id");
String name = set.getString("name");
String sex = set.getString("sex");
Date borndate = set.getDate("borndate");
String phone = set.getString("phone");
//把得到的resultset记录封装到actor对象,放入到list集合
list.add(new Actor(id, name, sex, borndate, phone));
}
System.out.println("list集合数据=" + list);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(null,preparedStatement,connection);
}
JDBCUtils.close(null,null,connection);
return list;
}
}