一、JDBC
1.定义
JDBC(Java Data Base Connectivity) 是 Java 访问数据库的标准规范.是一种用于执行SQL语句的Java API,可以为多种关系数据库提供统一访问,它由一组用Java语言编写的类和接口组成。是Java访问数据库的标准规范.
JDBC就是由sun公司定义的一套操作所有关系型数据库的规则(接口)。
二、JDBC 开发
public class JDBC01 {
public static void main(String[] args) throws ClassNotFoundException {
//1.注册驱动 forName 方法执行将类进行初始化
//从JDBC3开始,目前已经普遍使用的版本。可以不用注册驱动而直接使用。Class.forName这句话可以省略。
Class.forName("com.mysql.jdbc.Driver");
//2.获取连接 url,用户名, 密码
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "123456");
//3.获取 Statement对象
Statement statement = con.createStatement();
//4.执行创建表操作
String sql = "create table test01(id int, name varchar(20),age int);";
//5.增删改操作 使用executeUpdate,增加一张表
int i = statement.executeUpdate(sql);
//6.返回值是受影响的函数
System.out.println(i);
//7.关闭流
statement.close();
con.close();
}
}
public class JDBC02 {
public static void main(String[] args) throws SQLException {
//1.注册驱动 可以省略
//2.获取连接
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/db", "root", "123456");
//3.获取 Statement对象
Statement statement = con.createStatement();
String sql = "select * from jdbc_user";
//执行查询操作,返回的是一个 ResultSet 结果对象
ResultSet resultSet = statement.executeQuery(sql);
//4.处理结果集 使用while循环
while(resultSet.next()){
//获取id
int id = resultSet.getInt("id");
//获取姓名
String username = resultSet.getString("username");
//获取生日
Date birthday = resultSet.getDate("birthday");
System.out.println(id + " = " +username + " : " + birthday);
}
//关闭连接
resultSet.close();
statement.close();
con.close();
}
}
步骤总结:
①获取驱动(可以省略)
②获取连接
③获取Statement对象
④处理结果集(只在查询时处理)
⑤释放资源
1.JDBC实现增删改查
public class JDBCUtils {
//1. 定义字符串常量, 记录获取连接所需要的信息
public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/db?characterEncoding=UTF-8";
public static final String USER = "root";
public static final String PASSWORD = "123456";
//2. 静态代码块, 随着类的加载而加载
static{
try {
//注册驱动
Class.forName(DRIVERNAME);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//3.获取连接的静态方法
public static Connection getConnection(){
try {
//获取连接对象
Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
//返回连接对象
return connection;
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
//关闭资源的方法
public static void close(Connection con, Statement st){
if(con != null && st != null){
try {
st.close();
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement st, ResultSet rs){
if(rs != null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
close(con,st);
}
}
2.SQL注入问题
**定义:**让用户输入的密码和 SQL 语句进行字符串拼接。用户输入的内容作为了 SQL 语句语法的一部分,改变了 原有SQL 真正的意义,以上问题称为 SQL 注入 .
要解决 SQL 注入就不能让用户输入的密码和我们的 SQL 语句进 行简单的字符串拼接。
3.预处理对象
PreparedStatement 接口
● PreparedStatement 是 Statement 接口的子接口,继承于父接口中所有的方法。它是一个预编译的 SQL 语句对象.
● 预编译: 是指SQL 语句被预编译,并存储在 PreparedStatement 对象中。然后可以使用此对象多次高效地执行该语句。
public class TestLogin {
public static void main(String[] args) throws SQLException {
//1.获取连接
Connection connection = JDBCUtils.getConnection();
//2.获取Statement
Statement statement = connection.createStatement();
//3.获取用户输入的用户名和密码
Scanner sc = new Scanner(System.in);
System.out.println("请输入用户名: ");
String name = sc.nextLine();
System.out.println("请输入密码: ");
String pass = sc.nextLine();
System.out.println(pass);
//4.获取 PrepareStatement 预编译对象
//4.1 编写SQL 使用 ? 占位符方式
String sql = "select * from jdbc_user where username = ? and password = ?";
PreparedStatement ps = connection.prepareStatement(sql);
//4.2 设置占位符参数
ps.setString(1,name);
ps.setString(2,pass);
//5. 执行查询 处理结果集
ResultSet resultSet = ps.executeQuery();
if(resultSet.next()){
System.out.println("登录成功! 欢迎您: " + name);
}else{
System.out.println("登录失败!");
}
//6.释放资源
JDBCUtils.close(connection,statement,resultSet);
}
}
//分别使用 Statement对象 和 PreparedStatement对象进行插入操作
public class TestPS {
public static void main(String[] args) throws SQLException {
Connection con = JDBCUtils.getConnection();
//获取 Sql语句执行对象
Statement st = con.createStatement();
//插入两条数据
st.executeUpdate("insert into jdbc_user values(null,'张三','123','1992/12/26')");
st.executeUpdate("insert into jdbc_user values(null,'李四','123','1992/12/26')");
//获取预处理对象
PreparedStatement ps = con.prepareStatement("insert into jdbc_user values(?,?,?,?)");
//第一条数 设置占位符对应的参数
ps.setString(1,null);
ps.setString(2,"长海");
ps.setString(3,"qwer");
ps.setString(4,"1990/1/10");
//执行插入
ps.executeUpdate();
//第二条数据
ps.setString(1,null);
ps.setString(2,"小斌");
ps.setString(3,"1122");
ps.setString(4,"1990/1/10");
//执行插入
ps.executeUpdate();
//释放资源
st.close();
ps.close();
con.close();
}
}
Statement 与 PreparedStatement的区别
● Statement用于执行静态SQL语句,在执行时,必须指定一个事先准备好的SQL语句。
● PrepareStatement是预编译的SQL语句对象,语句中可以包含动态参数“?”,在执行时可以为“?”动态设置参数值。
● PrepareStatement可以减少编译次数提高数据库性能。
4.JDBC 控制事务
常用API
开发步骤
- 获取连接
- 开启事务
- 获取到 PreparedStatement , 执行两次更新操作
- 正常情况下提交事务
- 出现异常回滚事务
- 最后关闭资源
public class JDBCTransaction {
//JDBC 操作事务
public static void main(String[] args) {
Connection con = null;
PreparedStatement ps = null;
try {
//1. 获取连接
con = JDBCUtils.getConnection();
//2. 开启事务
con.setAutoCommit(false);
//3. 获取到 PreparedStatement 执行两次更新操作
//3.1 tom 账户 -500
ps = con.prepareStatement("update account set money = money - ? where name = ? ");
ps.setDouble(1,500.0);
ps.setString(2,"tom");
ps.executeUpdate();
//模拟tom转账后 出现异常
System.out.println(1 / 0);
//3.2 jack 账户 +500
ps = con.prepareStatement("update account set money = money + ? where name = ? ");
ps.setDouble(1,500.0);
ps.setString(2,"jack");
ps.executeUpdate();
//4. 正常情况下提交事务
con.commit();
System.out.println("转账成功!");
} catch (SQLException e) {
e.printStackTrace();
try {
//5. 出现异常回滚事务
con.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
} finally {
//6. 最后关闭资源
JDBCUtils.close(con,ps);
}
}
}
三、数据库连接池&DBUtils
1.DBCP连接池
连接数据库表的工具类, 采用DBCP连接池的方式来完成
● Java中提供了一个连接池的规则接口 : DataSource , 它是java中提供的连接池。
● 在DBCP包中提供了DataSource接口的实现类,我们要用的具体的连接池 BasicDataSource 类。
public class DBCPUtils {
//1.定义常量 保存数据库连接的相关信息
public static final String DRIVERNAME = "com.mysql.jdbc.Driver";
public static final String URL = "jdbc:mysql://localhost:3306/db?characterEncoding=UTF-8";
public static final String USERNAME = "root";
public static final String PASSWORD = "123456";
//2.创建连接池对象 (有DBCP提供的实现类)
public static BasicDataSource dataSource = new BasicDataSource();
//3.使用静态代码块进行配置
static{
dataSource.setDriverClassName(DRIVERNAME);
dataSource.setUrl(URL);
dataSource.setUsername(USERNAME);
dataSource.setPassword(PASSWORD);
}
//4.获取连接的方法
public static Connection getConnection() throws SQLException {
//从连接池中获取连接
Connection connection = dataSource.getConnection();
return connection;
}
//5.释放资源方法
public static void close(Connection con, Statement statement){
if(con != null && statement != null){
try {
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement statement, ResultSet resultSet){
if(con != null && statement != null && resultSet != null){
try {
resultSet.close();
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class TestDBCP {
public static void main(String[] args) throws SQLException {
//1.从DBCP连接池中拿到连接
Connection con = DBCPUtils.getConnection();
//2.获取Statement对象
Statement statement = con.createStatement();
//3.查询所有员工的姓名
String sql = "select ename from employee";
ResultSet resultSet = statement.executeQuery(sql);
//4.处理结果集
while(resultSet.next()){
String ename = resultSet.getString("ename");
System.out.println("员工姓名: " + ename);
}
//5.释放资源
DBCPUtils.close(con,statement,resultSet);
}
}
常见配置项
2.C3P0连接池
配置文件 c3p0-config.xml
<c3p0-config>
<!--默认配置-->
<default-config>
<!-- initialPoolSize:初始化时获取三个连接,
取值应在minPoolSize与maxPoolSize之间。 -->
<property name="initialPoolSize">3</property>
<!-- maxIdleTime:最大空闲时间,60秒内未使用则连接被丢弃。若为0则永不丢弃。-->
<property name="maxIdleTime">60</property>
<!-- maxPoolSize:连接池中保留的最大连接数 -->
<property name="maxPoolSize">100</property>
<!-- minPoolSize: 连接池中保留的最小连接数 -->
<property name="minPoolSize">10</property>
</default-config>
<!--配置连接池mysql-->
<named-config name="mysql">
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://localhost:3306/db5?characterEncoding=UTF-8</property>
<property name="user">root</property>
<property name="password">123456</property>
<property name="initialPoolSize">10</property>
<property name="maxIdleTime">30</property>
<property name="maxPoolSize">100</property>
<property name="minPoolSize">10</property>
</named-config>
<!--配置连接池2,可以配置多个-->
</c3p0-config>
C3P0提供的核心工具类, ComboPooledDataSource , 如果想使用连接池,就必须创建该类的对象
● new ComboPooledDataSource(); 使用 默认配置
● new ComboPooledDataSource(“mysql”); 使用命名配置
public class C3P0Utils {
//1.创建连接池对象 C3P0对DataSource接口的实现类
//使用指定的配置
public static ComboPooledDataSource dataSource = new ComboPooledDataSource("mysql");
//获取连接的方法
public static Connection getConnection() throws SQLException {
return dataSource.getConnection();
}
//释放资源
public static void close(Connection con, Statement statement){
if(con != null && statement != null){
try {
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement statement, ResultSet resultSet){
if(con != null && statement != null && resultSet != null){
try {
resultSet.close();
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class TestC3P0 {
//需求 查询姓名为李白的 记录
public static void main(String[] args) throws SQLException {
//1.获取连接
Connection con = C3P0Utils.getConnection();
//2.获取预处理对象
String sql = "select * from employee where ename = ?";
PreparedStatement ps = con.prepareStatement(sql);
//3.设置占位符的值
ps.setString(1,"李白");
ResultSet resultSet = ps.executeQuery();
//4.处理结果集
while(resultSet.next()){
int eid = resultSet.getInt("eid");
String ename = resultSet.getString("ename");
int age = resultSet.getInt("age");
String sex = resultSet.getString("sex");
double salary = resultSet.getDouble("salary");
Date date = resultSet.getDate("empdate");
System.out.println(eid +" " + ename + " " + age +" " + sex +" " + salary +" "+date);
}
//5.释放资源
C3P0Utils.close(con,ps,resultSet);
}
}
常见配置
3.Druid连接池
配置文件
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost/db?characterEncoding=UTF-8
username=root
password=123456
initialSize=5
maxActive=10
maxWait=3000
获取数据库连接池对象
● 通过工厂来来获取 DruidDataSourceFactory类的createDataSource方法
● createDataSource(Properties p) 方法参数可以是一个属性集对象
public class DruidUtils {
//1.定义成员变量
public static DataSource dataSource;
//2.静态代码块
static{
try {
//3.创建属性集对象
Properties p = new Properties();
//4.加载配置文件 Druid 连接池不能够主动加载配置文件 ,需要指定文件
InputStream inputStream = DruidUtils.class.getClassLoader().getResourceAsStream("druid.properties");
//5. 使用Properties对象的 load方法 从字节流中读取配置信息
p.load(inputStream);
//6. 通过工厂类获取连接池对象
dataSource = DruidDataSourceFactory.createDataSource(p);
} catch (Exception e) {
e.printStackTrace();
}
}
//获取连接的方法
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
return null;
}
}
//释放资源
public static void close(Connection con, Statement statement){
if(con != null && statement != null){
try {
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement statement, ResultSet resultSet){
if(con != null && statement != null && resultSet != null){
try {
resultSet.close();
statement.close();
//归还连接
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
public class TestDruid {
// 需求 查询 薪资在3000 到 5000之间的员工的姓名
public static void main(String[] args) throws SQLException {
//1.获取连接
Connection con = DruidUtils.getConnection();
//2.获取Statement对象
Statement statement = con.createStatement();
//3.执行查询
ResultSet resultSet = statement.executeQuery("select ename from employee where salary
between 3000 and 5000");
//4.处理结果集
while(resultSet.next()){
String ename = resultSet.getString("ename");
System.out.println(ename);
}
//5.释放资源
DruidUtils.close(con,statement,resultSet);
}
}
4.JavaBean组件
JavaBean 就是一个类, 开发中通常用于封装数据,有一下特点
● 需要实现 序列化接口, Serializable (暂时可以省略)
● 提供私有字段: private 类型 变量名;
● 提供 getter 和 setter
● 提供 空参构造
public class Employee implements Serializable {
private int eid;
private String ename;
private int age;
private String sex;
private double salary;
private Date empdate;
//空参 getter setter省略
}
QueryRunner核心类
构造方法
● QueryRunner()
● QueryRunner(DataSource ds) ,提供数据源(连接池),DBUtils底层自动维护连接connection
常用方法
● update(Connection conn, String sql, Object… params) ,用来完成表数据的增加、删除、更新操作
● query(Connection conn, String sql, ResultSetHandler rsh, Object… params) ,用来完成表
数据的查询操作
QueryRunner实现增、删、改操作
步骤
①创建QueryRunner(手动或自动)
②占位符方式 编写SQL
③设置占位符参数
④执行
//添加
@Test
public void testInsert() throws SQLException {
//1.创建 QueryRunner 手动模式创建
QueryRunner qr = new QueryRunner();
//2.编写 占位符方式 SQL
String sql = "insert into employee values(?,?,?,?,?,?)";
//3.设置占位符的参数
Object[] param = {null,"张百万",20,"女",10000,"1990-12-26"};
//4.执行 update方法
Connection con = DruidUtils.getConnection();
int i = qr.update(con, sql, param);
//5.释放资源
DbUtils.closeQuietly(con);
}
//修改
@Test
public void testUpdate() throws SQLException {
//1.创建QueryRunner对象 自动模式,传入数据库连接池
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
//2.编写SQL
String sql = "update employee set salary = ? where ename = ?";
//3.设置占位符参数
Object[] param = {0,"张百万"};
//4.执行update, 不需要传入连接对象
qr.update(sql,param);
}
//删除
@Test
public void testDelete() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "delete from employee where eid = ?";
//只有一个参数,不需要创建数组
qr.update(sql,1);
}
5.QueryRunner实现查询操作
1.查询id为5的记录,封装到数组中
@Test
public void testFindById() throws SQLException {
//1.创建QueryRunner
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
//2.编写SQL
String sql = "select * from employee where eid = ?";
//3.执行查询
Object[] query = qr.query(sql, new ArrayHandler(), 5);
//4.获取数据
System.out.println(Arrays.toString(query));
}
2.查询所有数据,封装到List集合中
@Test
public void testFindAll() throws SQLException {
//1.创建QueryRunner
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
//2.编写SQL
String sql = "select * from employee";
//3.执行查询
List<Object[]> query = qr.query(sql, new ArrayListHandler());
//4.遍历集合获取数据
for (Object[] objects : query) {
System.out.println(Arrays.toString(objects));
}
}
3.根据ID查询,封装到指定JavaBean中
@Test
public void testFindByIdJavaBean() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "select * from employee where eid = ?";
Employee employee = qr.query(sql, new BeanHandler<Employee>(Employee.class), 3);
System.out.println(employee);
}
4.查询薪资大于 3000 的所员工信息,封装到JavaBean中再封装到List集合中
@Test
public void testFindBySalary() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "select * from employee where salary > ?";
List<Employee> list = qr.query(sql, new BeanListHandler<Employee>(Employee.class),
3000);
for (Employee employee : list) {
System.out.println(employee);
}
}
5.查询姓名是 张百万的员工信息,将结果封装到Map集合中
@Test
public void testFindByName() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "select * from employee where ename = ?";
Map<String, Object> map = qr.query(sql, new MapHandler(), "张百万");
Set<Map.Entry<String, Object>> entries = map.entrySet();
for (Map.Entry<String, Object> entry : entries) {
//打印结果
System.out.println(entry.getKey() +" = " +entry.getValue());
}
}
- 查询所有员工的薪资总额
@Test
public void testGetSum() throws SQLException {
QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
String sql = "select sum(salary) from employee";
Double sum = (Double)qr.query(sql, new ScalarHandler<>());
System.out.println("员工薪资总额: " + sum);
}
6.数据库批处理
mysql 批处理是默认关闭的,所以需要加一个参数才打开mysql 数据库批处理,在url中添加。
rewriteBatchedStatements=true
如:
url=jdbc:mysql://127.0.0.1:3306/db?characterEncoding=UTF-8&rewriteBatchedStatements=true
public class TestBatch {
//使用批处理,向表中添加 1万条数据
public static void main(String[] args) {
try {
//1.获取连接
Connection con = DruidUtils.getConnection();
//2.获取预处理对象
String sql ="insert into testBatch(uname) values(?)";
PreparedStatement ps = con.prepareStatement(sql);
//3.创建 for循环 来设置占位符参数
for (int i = 0; i < 10000 ; i++) {
ps.setString(1,"小强"+i);
//将SQL添加到批处理 列表
ps.addBatch();
}
//添加时间戳 测试执行效率
long start = System.currentTimeMillis();
//统一 批量执行
ps.executeBatch();
long end = System.currentTimeMillis();
System.out.println("插入10000条数据使用: " +(end - start) +" 毫秒!");
} catch (SQLException e) {
e.printStackTrace();
}
}
}