狂神老师的视频通俗易懂,但是需要明白的是,视频只是学习的捷径,真正实打实的学习还是得看书、看官方文档!
一、数据库驱动
我们的程序会通过 数据库 驱动,和数据库打交道!
二、JDBC
SUN 公司为了简化 开发人员的(对数据库的)操作,提供了一个(Java操作数据库的)规范,俗称 JDBC 这些规范的实现由具体的厂商去做~
对于开发人员来说,我们只需要掌握 JDBC 接口的操作即可!
java.sql
javax.sql
还需要一个数据库驱动包 mysql-connector-java-8.0.27.jar (官网下载MySQL :: Download Connector/J)
三、第一个 JDBC 程序
-
准备 mysql 数据库环境
-
创建一个普通项目
-
导入数据库驱动包
-
编写测试代码
加载驱动属于比较老的方式
package com.fengluo.lesson01;
import java.sql.*;
// 我的第一个 JDBC 程序
public class JDBCDemo01 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
// 1. 引入依赖
// 2. 加载驱动
Class.forName("com.mysql.cj.jdbc.Driver"); // 固定写法,加载驱动
// 3. 用户信息和url,连接数据库成功,数据库对象
String url = "jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf8&useSSL=true";
String userName = "root";
String password = "123456";
Connection connection = DriverManager.getConnection(url, userName, password);
// 4. 创建预编译语句,设置SQL对象
// 5. 设置参数
Statement statement = connection.createStatement();
String sql = "SELECT * FROM user_info";
// 6. 执行 sql
ResultSet resultSet = statement.executeQuery(sql); // 返回的结果集
while (resultSet.next()) {
System.out.println("id=" + resultSet.getObject("id"));
System.out.println("user_name=" + resultSet.getObject("user_name"));
System.out.println("password=" + resultSet.getObject("password"));
System.out.println("phone=" + resultSet.getObject("phone"));
System.out.println("email=" + resultSet.getObject("email"));
}
// 7. 关闭连接,释放资源
resultSet.close();
statement.close();
connection.close();
}
}
成功获取!
步骤总结:
- 加载驱动
- 连接数据库 DriverManager
- 获得执行 sql 的对象 Statement
- 获得返回的结果集
- 释放连接
DriverManager
Class.forName("com.mysql.cj.jdbc.Driver"); // 固定写法,加载驱动
Connection connection = DriverManager.getConnection(url, userName, password);
// connection 代表数据库
// 数据库设置自动提交
// 事务提交 事务回滚
connection.rollback();
connection.commit();
connection.setAutoCommit();
URL
String url = "jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf8&useSSL=true";
// mysql --3306
// jdbc:mysql://主机地址:端口号/数据库名?useUnicode=true&characterEncoding=utf8&useSSL=true
// oracle -- 1521
// jdbc:oracle:thin:@localhost:1521:sid
Statement 执行 SQL 的对象,PrepareStatement 执行 SQL 的对象
String sql = "SELECT * FROM user_info";
statement.executeQuery(); // 查询操作,操作返回 ResultSet
statement.execute(); // 执行任何 SQL,相对效率较低
statement.executeUpdate(); // 更新、插入、删除,都是用这个,返回一个受影响的行数
ResultSet 查询的结果集:封装了所有的查询结果
获得指定的数据类型
resultSet.getObject(); // 在不知道列类型的情况下使用
// 如果知道列的类型就是用指定的类型
resultSet.getString();
resultSet.getInt();
……
遍历,指针
resultSet.beforeFirst(); // 移动到最前面
resultSet.afterLast(); // 移动到最后面
resultSet.next(); // 移动到下一个数据
resultSet.previous(); // 移动到前一行
resultSet.absolute(row); // 移动到指定行
释放资源
resultSet.close();
statement.close();
connection.close();
四、工具类
package com.fengluo.lesson01.utils;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
static {
try{
InputStream in = JDBCUtils.class.getClassLoader().getResourceAsStream("dp.properties");
Properties properties = new Properties();
properties.load(in);
driver = properties.getProperty("driver");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
// 1. 驱动只用加载一次
Class.forName(driver);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url, username, password);
}
// 释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
driver = com.mysql.jdbc.Driver
url = jdbc:mysql://localhost:3306/study?useUnicode=true&characterEncoding=utf8&useSSL=true
username = root
password = 123456
五、statement对象
JDBC 中的 statement 对象用于向数据库发送 SQL 语句,想完成对数据库的增删改查,只需要通过这个对象向数据库发送增删改查语句即可。
Statement 对象的 executeUpdate 方法,用于向数据库发送增删改查语句的 sql 语句,executeUpdate 执行完成后,将会返回一个整数(即增删改语句导致数据库几行数据发生了改变)
Statement.executeQuery 方法用于向数据库发送查询语句,executeQuery 方法返回代表查询结果的 ResultSet 对象。
CRUD 操作-create
使用 executeUpdate(String sql) 方法完成数据添加操作,示例操作:
connection = JDBCUtils.getConnection(); // 获取数据库连接
statement = connection.createStatement(); // 获得 SQL 的执行对象
String sql = "INSERT INTO user_info(id, `user_name`, `password`, `phone`, `email`)" +
"VALUES (2, 'fengluo', '123456', '12345678910', '123456789@qq.com')";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("插入成功");
}
CRUD 操作-read
使用 executeQuery(String sql)方法完成数据查询操作,示例操作:
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "SELECT * from user_info where id = 1";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
// 根据获得列的数据类型,分别调用 rs 的相应方法映射到 java 对象中
System.out.println(resultSet.getString("user_name"));
}
CRUD 操作-update
使用 executeUpdate(String sql) 方法完成数据修改操作,示例操作:
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "UPDATE user_info SET `password`='321654', `email`='321654@qq.com' WHERE id=1";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("修改成功");
}
CRUD 操作-delete
使用 executeUpdate(String sql) 方法完成数据删除操作,示例操作:
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "Delete from user_info WHERE id=2";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("删除成功");
}
代码实现
- 增删改的方法,executeUpdate
package com.fengluo.lesson01;
import com.fengluo.lesson01.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestInsert {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet =null;
try {
connection = JDBCUtils.getConnection(); // 获取数据库连接
statement = connection.createStatement(); // 获得 SQL 的执行对象
String sql = "INSERT INTO user_info(id, `user_name`, `password`, `phone`, `email`)" +
"VALUES (2, 'fengluo', '123456', '12345678910', '123456789@qq.com')";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils.release(connection, statement, resultSet);
}
}
}
package com.fengluo.lesson01;
import com.fengluo.lesson01.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDelete {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "Delete from user_info WHERE id=2";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("删除成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils.release(connection, statement, resultSet);
}
}
}
package com.fengluo.lesson01;
import com.fengluo.lesson01.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestUpdate {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "UPDATE user_info SET `password`='321654', `email`='321654@qq.com' WHERE id=1";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("更新成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils.release(connection, statement, resultSet);
}
}
}
- 查询,executeQuery
package com.fengluo.lesson01;
import com.fengluo.lesson01.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestSelect {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
statement = connection.createStatement();
String sql = "SELECT * from user_info where id = 1";
resultSet = statement.executeQuery(sql);
while (resultSet.next()) {
System.out.println(resultSet.getString("user_name"));
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils.release(connection, statement, resultSet);
}
}
}
SQL 注入的问题
SQL 存在漏洞,会被攻击导致数据泄露,SQL会被拼接 or
六、PrepareStatement 对象
PrepareStatement 可以防止 SQL 注入,并且效率更高!
七、IDEA 连接数据库
选择 MySQL
输入数据库账号密码,测试连接
选择需要的数据库模式
更新数据
SQL 控制台,编写 sql 语句
八、事务
要么都成功,要么都失败
ACID原则
原子性:要么全部完成,要么都不完成
一致性:总数不变
隔离性:多个进程互不干扰
持久性:一旦提交不可逆,持久化到数据库了
隔离性的问题:
脏读:一个事务读取了另一个没有提交的事务
不可重复读:在同一个事务内,重复读取表中的数据 ,表数据发生了改变
虚度(幻读):在一个事务内,读取到了别人插入的数据,导致前后读出来的结果不一致
代码实现
- 开启事务 connection.setAutoCommit(false);
- 一组业务执行完毕,提交事务
- 可以在catch语句中显示的定义 回滚语句,但默认失败就会回滚
package lesson04;
import com.fengluo.lesson01.utils.JDBCUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class TestTransAction {
public static void main(String[] args) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
connection = JDBCUtils.getConnection();
// 关闭数据库的自动提交,自动开启事务
connection.setAutoCommit(false); // 开启事务
String sql1 = "update account set money=money-100 where name='A'";
preparedStatement = connection.prepareStatement(sql1);
preparedStatement.executeUpdate();
String sql2 = "update account set money=money+100 where name='B'";
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate();
// 业务完毕,操作成功
connection.commit();
System.out.println("成功");
} catch (SQLException throwables) {
connection.rollback(); // 失败则回滚
throwables.printStackTrace();
} finally {
JDBCUtils.release(connection, preparedStatement, resultSet);
}
}
}
九、数据库连接池
数据库连接 – 执行完毕 – 释放
连接 – 释放的过程十分浪费系统资源
池化技术:准备一些预先的资源,过来就链接预先准备好的
最少连接数:10
最大连接数:15 业务最高承载上限
等待超时:100ms
编写连接池,实现一个接口 DataSource
开源数据源实现
DBCP
C3P0
Druid
使用了这些数据库连接池之后,我们在项目开发中就不需要编写连接数据库的代码了!
DBCP
DBCP连接池的jar包下载与IDEA配置_Java攻城狮修炼中-优快云博客
DBCP工具类:
package lesson04.utils;
import org.apache.commons.dbcp2.BasicDataSource;
import org.apache.commons.dbcp2.BasicDataSourceFactory;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils_DBCP {
private static String driver = null;
private static String url = null;
private static String username = null;
private static String password = null;
private static BasicDataSource dataSource = null;
static {
try{
InputStream in = JDBCUtils_DBCP.class.getClassLoader().getResourceAsStream("dbcpconfig.properties");
Properties properties = new Properties();
properties.load(in);
// 创建数据源 工厂模式 --> 创建
dataSource = BasicDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection(); // 从数据源中获取连接
}
// 释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
测试 DBCP 工具类:
package lesson04;
import com.fengluo.lesson01.utils.JDBCUtils;
import lesson04.utils.JDBCUtils_DBCP;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class TestDBCP {
public static void main(String[] args) throws SQLException {
Connection connection = null;
Statement statement = null;
ResultSet resultSet =null;
try {
connection = JDBCUtils_DBCP.getConnection(); // 获取数据库连接
statement = connection.createStatement(); // 获得 SQL 的执行对象
String sql = "INSERT INTO user_info(id, `user_name`, `password`, `phone`, `email`)" +
"VALUES (3, 'fengluo', '123456', '12345678910', '123456789@qq.com')";
int i = statement.executeUpdate(sql);
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils_DBCP.release(connection, statement, resultSet);
}
}
}
C3P0
配置 C3P0 所需的 jar 包 官网下载
C3P0 配置文件
<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
<default-config>
<property name="user">root</property>
<property name="password">1234</property>
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql:///kjxn</property>
</default-config> <!-- This app is massive! -->
<!--c3p0的命名配置,如果在代码中ComboPooledDataSource ds=new ComboPooledDataSource(MySQL);这样写就表示使用的是mysql的缺省(默认)-->
<named-config name="MySQL">
<property name="driverClass">com.mysql.cj.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/study?userUnicode=true&characterEncoding=utf8&uesSSL=true&serverTimezone=UTC</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="acquiredIncrement">5</property>
<property name="initialPoolSize">10</property>
<property name="minPoolSize">5</property>
<property name="maxPoolSize">20</property>
</named-config>
</c3p0-config>
package lesson04.utils;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class JDBCUtils_C3P0 {
private static ComboPooledDataSource dataSource = null;
static {
try{
// 创建数据源 工厂模式 --> 创建
dataSource = new ComboPooledDataSource("MySQL"); //配置文件写法
} catch (Exception e) {
e.printStackTrace();
}
}
// 获取连接
public static Connection getConnection() throws SQLException {
return dataSource.getConnection(); // 从数据源中获取连接
}
// 释放连接资源
public static void release(Connection connection, Statement statement, ResultSet resultSet) throws SQLException {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (connection != null) {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
package lesson04;
import com.fengluo.lesson01.utils.JDBCUtils;
import lesson04.utils.JDBCUtils_C3P0;
import lesson04.utils.JDBCUtils_DBCP;
import java.sql.*;
public class TestC3P0 {
public static void main(String[] args) throws SQLException {
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet =null;
try {
connection = JDBCUtils_C3P0.getConnection(); // 获取数据库连接
String sql = "INSERT INTO user_info(id, `user_name`, `password`, `phone`, `email`)" +
"VALUES (?, ?, ?, ?, ?)";
preparedStatement = connection.prepareStatement(sql);
// 手动给参数赋值
preparedStatement.setInt(1, 5);
preparedStatement.setString(2, "fengluo");
preparedStatement.setString(3, "123654");
preparedStatement.setString(4, "123465987");
preparedStatement.setString(5, "123465@qq.com");
int i = preparedStatement.executeUpdate();
if (i > 0) {
System.out.println("插入成功");
}
} catch (SQLException throwables) {
throwables.printStackTrace();
} finally {
JDBCUtils_DBCP.release(connection, preparedStatement, resultSet);
}
}
}
结论
无论使用什么数据源,本质上还是一样的,DataSource 接口不会变,方法就不会变