哈喽!大家好,我是小简。今天开始学习《Java-JDBC》,此系列是我做的一个 “Java 从 0 到 1 ” 实验,给自己一年左右时间,按照我自己总结的 Java-学习路线,从 0 开始学 Java 知识,并不定期更新所学笔记,期待一年后的蜕变吧!
JDBC的全称是Java数据库连接(Java DataBase Connectivity),它是一套用于执行SQL语句的Java API。 Java程序员使用JDBC可以连接任何提供了JDBC驱动程序的数据库系统,从而完成对数据库的各种操作。
Java程序 JDBC API 使用 JDBC 驱动管理器并指定数据库的 JDBC 驱动器来提供与数据库的连接。
JDBC 程序实例
前置工作:
Mysql驱动下载:MySQL :: Download Connector,选择操作系统:Platform Independent
在项目下创建一个文件夹 libs 将下载的 mysql.jar 驱动拷贝到该目录下,在 IDEA 中右键点击 mysql.jar 选择 add to Library (加入到项目中)
package com.jwt.jdbc;
import com.mysql.jdbc.Driver;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
public class myjdbc {
public static void main(String[] args) throws SQLException {
//1. 注册驱动
Driver driver = new Driver(); //创建driver 对象
//2. 得到连接
String url = "jdbc:mysql://localhost:3306/jwt";
//将用户名和密码放入到Properties对象
Properties info = new Properties();
info.setProperty("user", "root");// 用户
info.setProperty("password", "root"); //密码
Connection connect = driver.connect(url, info);
//3. 执行sql
String sql = "insert into jwt.jwt_info value (3,'Pyj') ";
//statement 用于执行静态SQL语句并返回其生成的结果的对象
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql); // dml(update insert delete)语句,返回的就是影响行数
System.out.println(rows > 0 ? "成功" : "失败");
//4. 关闭连接资源
statement.close();
connect.close();
}
}
//1. 注册驱动
Driver driver = new Driver();
String url = "jdbc:mysql://localhost:3306/jwt";
//将用户名和密码放入到Properties对象
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","root");
//2. 得到连接
Connection connection = driver.connect(url, properties);
//使用反射加载Driver类, 动态加载,更加的灵活,减少依赖性
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//将用户名和密码放入到Properties对象
String url = "jdbc:mysql://localhost:3306/jwt";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","root");
//得到连接
Connection connection = driver.connect(url, properties);
//使用DriverManager替代driver进行统一管理
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url 和user 和password
String url = "jdbc:mysql://localhost:3306/jwt";
String user = "root";
String password = "root";
//注册Driver驱动
DriverManager.registerDriver(driver);
//得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//使用Class.forName自动完成注册驱动,简化代码
Class.forName("com.mysql.jdbc.Driver");
//创建url 和user 和password
String url = "jdbc:mysql://localhost:3306/jwt";
String user = "root";
String password = "root";
//得到连接
Connection connection = DriverManager.getConnection(url, user, password);
第一步:src下新建文件mysql.properties
url=jdbc:mysql://localhost:3306/jwt
user=root
password=root
driver=com.mysql.jdbc.Driver
第二步:
//在方式4的基础上改进,增加配置文件,让连接mysql更加灵活
//通过Properties 对象获取配置文件的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src//mysql.properties"));//windows路径的//改成\\
//获取相关的值
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);
DBMS | JDBC驱动程序名称 | URL格式 |
---|---|---|
MySQL | com.mysql.jdbc.Driver | jdbc:mysql://hostname:port/databaseName |
Oracle | oracle.jdbc.driver.OracleDriver | jdbc:oracle:thin:@hostname:port:databaseName |
PostgreSQL | org.postgresql.Driver | jdbc:postgresql://hostname:port/dbname |
DB2 | com.ibm.db2.jdbc.net.DB2Driver | jdbc:db2:hostname:port/databaseName |
Sybase | com.sybase.jdbc.SybDriver | jdbc:sybase:Tds:hostname: port/databaseName |
package com.jwt.jdbc;
import com.mysql.jdbc.Driver;
import org.junit.Test;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;
public class jdbcConn {
//方式1
@Test
public void connect01() throws SQLException {
//1. 注册驱动
Driver driver = new Driver();
//2. 得到连接
String url = "jdbc:mysql://localhost:3306/jwt";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","root");
Connection connection = driver.connect(url, properties);
System.out.println("第1种方式:"+connection);
}
//方式2 使用反射加载Driver类
@Test
public void connect02() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver类, 动态加载,更加的灵活,减少依赖性
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/jwt";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","root");
Connection connection = driver.connect(url, properties);
System.out.println("第2种方式:"+connection);
}
//方式3 使用DriverManager 替代driver 进行统一管理
@Test
public void connect03() throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
//使用反射加载Driver
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
//创建url 和user 和password
String url = "jdbc:mysql://localhost:3306/jwt";
String user = "root";
String password = "root";
//注册Driver驱动
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第3种方式:"+connection);
}
//方式4: 使用Class.forName 自动完成注册驱动,简化代码
@Test
public void connect04() throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");
//创建url 和user 和password
String url = "jdbc:mysql://localhost:3306/jwt";
String user = "root";
String password = "root";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第4种方式:"+connection);
}
//方式5: 在方式4 的基础上改进,增加配置文件,让连接mysql 更加灵活
@Test
public void connect05() throws ClassNotFoundException, SQLException, IOException {
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");
Class.forName(driver);//建议写上
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("第5种方式:"+connection);
}
}
package com.jwt.jdbc;
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;
import java.sql.ResultSet;
public class ResultSet_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
//通过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");
//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 from jwt_info";
ResultSet resultSet = statement.executeQuery(sql);//该语句返回单个ResultSet对象
//5. 使用while 取出数据
while (resultSet.next()) { // 让光标向后移动,如果没有更多行,则返回false
int id = resultSet.getInt(1); //通过索引获取该行的第1列
//String name = resultSet.getString(2);//通过索引获取该行的第2列
String name = resultSet.getString("name");//通过列名获取该行的第2列
System.out.println(id + "\t" + name + "\t" );
}
//6. 关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
存在SQL注入风险
package com.jwt.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
public class Statement_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输入管理员的名字: "); //next(): 当接收到空格或者'就是表示结束
String admin_name = scanner.nextLine(); //如果希望看到SQL 注入,这里需要用nextLine
System.out.print("请输入管理员的密码: ");
String admin_pwd = scanner.nextLine();
//通过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");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到Statement
Statement statement = connection.createStatement();
//4. 组织SqL
String sql = "select name , password from user where name ='"
+ admin_name + "' and password = '" + admin_pwd + "'";
ResultSet resultSet = statement.executeQuery(sql);
if (resultSet.next()) { //如果查询到一条记录,则说明该管理存在
System.out.println("恭喜, 登录成功");
} else {
System.out.println("对不起,登录失败");
}
//关闭连接
resultSet.close();
statement.close();
connection.close();
}
}
正常登陆
请输入管理员的名字: Tom
请输入管理员的密码: 123
恭喜, 登录成功
Sql注入登陆
请输入管理员的名字: Tom' or
请输入管理员的密码: or '1'='1
恭喜, 登录成功
PreparedStatement接口扩展了Statement接口,它添加了比Statement对象更好一些优点的功能。此语句可以动态地提供/接受参数。
预处理的好处
package com.jwt.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
public class PreparedStatement_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输入管理员的名字: "); //next(): 当接收到空格或者'就是表示结束
String admin_name = scanner.nextLine(); //如果希望看到SQL注入,这里需要用nextLine
System.out.print("请输入管理员的密码: ");
String admin_pwd = scanner.nextLine();
//通过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");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到PreparedStatement
//3.1 组织SqL , Sql 语句的? 就相当于占位符
String sql = "select name , password from user where name = ? and password = ?";
//3.2 preparedStatement 对象实现了PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3 给?赋值
preparedStatement.setString(1, admin_name);
preparedStatement.setString(2, admin_pwd);
//4. 执行select 语句使用executeQuery
// 如果执行的是dml(update, insert ,delete)使用executeUpdate()
// 这里执行executeQuery ,不要在写sql
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()) { //如果查询到一条记录,则说明该管理存在
System.out.println("恭喜, 登录成功");
} else {
System.out.println("对不起,登录失败");
}
//关闭连接
resultSet.close();
preparedStatement.close();
connection.close();
}
}
正常登陆
请输入管理员的名字: Tom
请输入管理员的密码: 123
恭喜, 登录成功
Sql注入登陆
请输入管理员的名字: Tom' or
请输入管理员的密码: or '1'='1
对不起,登录失败
package com.jwt.jdbc;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
import java.util.Scanner;
public class PreparedStatement_ {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
Scanner scanner = new Scanner(System.in);
//让用户输入管理员名和密码
System.out.print("请输入管理员的名字: "); //next(): 当接收到空格或者'就是表示结束
String admin_name = scanner.nextLine(); //如果希望看到SQL 注入,这里需要用nextLine
System.out.print("请输入管理员的密码: ");
String admin_pwd = scanner.nextLine();
//通过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");
//1. 注册驱动
Class.forName(driver);//建议写上
//2. 得到连接
Connection connection = DriverManager.getConnection(url, user, password);
//3. 得到PreparedStatement
//3.1 组织SqL , Sql 语句的? 就相当于占位符
String sql = "insert into user values (?,?)";
//3.2 preparedStatement 对象实现了PreparedStatement 接口的实现类的对象
PreparedStatement preparedStatement = connection.prepareStatement(sql);
//3.3 给?赋值
preparedStatement.setString(1, admin_name);
preparedStatement.setString(2, admin_pwd);
//4. 执行dml(update, insert ,delete),使用executeUpdate()
int rows = preparedStatement.executeUpdate();//不要写sql
System.out.println(rows > 0 ? "执行成功" : "执行失败");
//关闭连接
preparedStatement.close();
connection.close();
}
}
在JDBC操作时,获取连接和释放连接会经常使用,可以将其封装到JDBC连接的工具类JDBCUtils
package com.jwt.jdbc;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
//定义相关的属性(4 个), 因为只需要一份,因此,我们做出static
private static String user; //用户名
private static String password; //密码
private static String url; //url
private static String driver; //驱动名
//在static 代码块去初始化
static {
try {
Properties properties = new Properties();
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
4. 如果需要关闭资源,就传入对象,否则传入null
*/
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);
}
}
}
package com.jwt.jdbc;
import org.junit.Test;
import java.sql.*;
public class JDBCUtils_Use {
@Test
public void testDML() {//insert , update, delete
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "update user set name = ? where id = ?";
PreparedStatement preparedStatement = null;
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//给占位符赋值
preparedStatement.setString(1, "Bob");
preparedStatement.setInt(2, 1);
//执行
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
}
package com.jwt.jdbc;
import org.junit.Test;
import java.sql.*;
public class JDBCUtils_Use {
@Test
public void testSelect() throws SQLException {
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from user where id = ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();
// System.out.println(connection.getClass()); //com.mysql.jdbc.JDBC4Connection
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 password = set.getString("password");
Date birthday = set.getDate("birthday");
System.out.println(id + "\t" + name + "\t" + password + "\t" + birthday);
}
}catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(set, preparedStatement, connection);
}
}
}
create table account(
id int primary key auto_ increment,
name varchar(32) not null default '',
balance double not null default 0) character set utf8;
insert into account values(null, '马云', 3000);
insert into account values(null, '马化腾', 10000);
package com.jwt.jdbc.transaction_;
import com.jwt.jdbc.JDBCUtils;
import org.junit.Test;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
public class Transaction_ {
//没有使用事务,100会凭空消失
@Test
public void noTransaction(){
//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";
PreparedStatement preparedStatement = null;
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();// 在默认情况下,connection 是默认自动提交
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();// 执行第1条sql
int i = 1 / 0; //抛出异常
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate(); // 执行第2条sql
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
//事务来解决
@Test
public void useTransaction() {
//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";
PreparedStatement preparedStatement = null;
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtils.getConnection();// 在默认情况下,connection 是默认自动提交
//将connection 设置为不自动提交
connection.setAutoCommit(false); //开启了事务
preparedStatement = connection.prepareStatement(sql);
preparedStatement.executeUpdate();// 执行第1条sql
// int i = 1 / 0; //抛出异常
preparedStatement = connection.prepareStatement(sql2);
preparedStatement.executeUpdate(); // 执行第2条sql
connection.commit();
} catch (SQLException e) {
try {
//这里我们可以进行回滚,即撤销执行的SQL
//默认回滚到事务开始的状态.
System.out.println("执行发生了异常,撤销执行的sql");
connection.rollback();
} catch (SQLException ex) {
ex.printStackTrace();
}
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
}
基本介绍 1、当需要成批插入或者更新记录时。 可以采用Java的批量更新机制,这一机制允许多条语句一次性提交给数据库批量处理。通常情况下比单独提交处理更有效率。 2、JDBC的批量处理语句包括下面方法:
3、JDBC连接MySQL时, 如果要使用批处理功能,请再url中加参数**?rewriteBatchedStatements=true**
4、批处理往往和PreparedStatement一搭配使用,可以既减少编译次数,又减少运行次数,效率大大提高
package com.jwt.jdbc;
import org.junit.Test;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.Properties;
public class Batch_ {
//传统方法,添加5000 条数据到admin2
@Test
public void noBatch() throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src//mysql.properties"));//windows路径的//改成\\
//获取相关的值
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Connection connection = DriverManager.getConnection(url,user,password);
String sql = "insert into jwt_info values(?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 5000; i++) {//5000 执行
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "jack" + i);
preparedStatement.executeUpdate();
}
long end = System.currentTimeMillis();
System.out.println("传统的方式耗时=" + (end - start) + "ms") ;//传统的方式耗时=385ms
//关闭连接
preparedStatement.close();
connection.close();
}
//使用批量方式添加数据
@Test
public void batch() throws Exception {
Properties properties = new Properties();
properties.load(new FileInputStream("src//mysql.properties"));//windows路径的//改成\\
//获取相关的值
String url = properties.getProperty("url");
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String driver = properties.getProperty("driver");
Connection connection = DriverManager.getConnection(url,user,password);
String sql = "insert into jwt_info values(?, ?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();//开始时间
for (int i = 0; i < 5000; i++) {//5000 执行
preparedStatement.setInt(1, i);
preparedStatement.setString(2, "jack" + i);
preparedStatement.addBatch();
//当有1000 条记录时,在批量执行
if((i + 1) % 1000 == 0) {//满1000 条sql
preparedStatement.executeBatch();
//清空一把
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println("批量方式耗时=" + (end - start) + "ms");//批量方式耗时=60ms
//关闭连接
preparedStatement.close();
connection.close();
}
}
为了解决传统开发中的数据库连接问题,可以采用数据库连接池技术(connection pool)
方式一和二都需要:
将下载的 c3p0.jar 驱动拷贝到 libs 目录下,在 IDEA 中右键点击 c3p0.jar 选择 add to Library (加入到项目中)
方式二还需要:
将c3p0提供的 c3p0.config.xml 拷贝到 src 目录下,该文件指定了连接数据库和连接池的相关参数
在程序中指定 user, url , password 等相关参数来完成
package com.jwt.jdbc.datasource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class C3P0_ {
//方式1:在程序中指定 user, url , password 等相关参数
@Test
public void testC3P0_01() throws IOException, PropertyVetoException, SQLException {
//1. 创建一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
//2. 通过配置文件mysql.properties 获取相关连接的信息
Properties properties = new Properties();
properties.load(new FileInputStream("src//mysql.properties"));
//读取相关的属性值
String user = properties.getProperty("user");
String password = properties.getProperty("password");
String url = properties.getProperty("url");
String driver = properties.getProperty("driver");
//给数据源comboPooledDataSource 设置相关的参数
//注意:连接管理是由comboPooledDataSource 来管理
comboPooledDataSource.setDriverClass(driver);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setUser(user);
comboPooledDataSource.setPassword(password);
//设置初始化连接数
comboPooledDataSource.setInitialPoolSize(10);
//最大连接数
comboPooledDataSource.setMaxPoolSize(50);
//测试连接池的效率, 测试对mysql 5000 次操作
long start = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource 接口实现的
//System.out.println("连接OK");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("c3p0的第一种方式连接mysql 50000次耗时=" + (end - start));
//c3p0的第一种方式连接mysql 5000次耗时=516
}
}
使用配置文件模板来完成
package com.jwt.jdbc.datasource;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.junit.Test;
import java.beans.PropertyVetoException;
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;
public class C3P0_ {
//方式2:使用配置文件模板来完成
@Test
public void testC3P0_02() throws SQLException {
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("jwt_c3p0");
//测试连接池的效率, 测试对mysql 5000 次操作
long start = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Connection connection = comboPooledDataSource.getConnection();//这个方法就是从DataSource 接口实现的
//System.out.println("连接OK~");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("c3p0的第二种方式连接mysql 50000次耗时=" + (end - start));
//c3p0的第二种方式连接mysql 5000次耗时=512
}
}
#key=value
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/jwt?rewriteBatchedStatements=true
#url=jdbc:mysql://localhost:3306/jwt
username=root
password=root
#initial connection Size
initialSize=10
#min idle connecton size
minIdle=5
#max active connection size
maxActive=20
#max wait time (5000 mil seconds)
maxWait=5000
package com.jwt.jdbc.datasource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import javax.sql.DataSource;
import java.io.FileInputStream;
import java.sql.Connection;
import java.util.Properties;
public class Druid_ {
@Test
public void testDruid() throws Exception {
//1. 创建Properties 对象, 读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src//druid.properties"));
//2. 创建一个指定参数的数据库连接池, Druid 连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
long start = System.currentTimeMillis();
for (int i = 0; i < 50000; i++) {
Connection connection = dataSource.getConnection();
//System.out.println(connection.getClass());
//System.out.println("连接成功!");
connection.close();
}
long end = System.currentTimeMillis();
System.out.println("Druid 连接池操作50000次 mysql 耗时=" + (end - start));
//Druid 连接池操作50000次 mysql 耗时=329
}
}
package com.jwt.jdbc.datasource;
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;
public class JDBCUtilsByDruid {
private static DataSource ds;
//在静态代码块完成ds 初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src//druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写getConnection 方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接, 强调:在数据库连接池技术中,close 不是真的断掉连接
//而是把使用的Connection 对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package com.jwt.jdbc.datasource;
import org.junit.Test;
import java.sql.*;
public class JDBCUtilsByDruid_Use {
@Test
public void testSelect() {
System.out.println("使用 druid 方式完成");
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from user where id = ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtilsByDruid.getConnection();
System.out.println(connection.getClass());//运行类型com.alibaba.druid.pool.DruidPooledConnection
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 password = set.getString("password");
Date birthday = set.getDate("birthday");
System.out.println(id + "\t" + name + "\t" + password + "\t" + birthday);
}
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(set, preparedStatement, connection);
}
}
}
package com.jwt.jdbc.datasource;
import org.junit.Test;
import java.sql.*;
import java.util.ArrayList;
public class JDBCUtilsByDruid_Use {
//使用老师的土方法来解决ResultSet =封装=> Arraylist
@Test
public void testSelectToArrayList() {
System.out.println("使用druid 方式完成");
//1. 得到连接
Connection connection = null;
//2. 组织一个sql
String sql = "select * from user where id >= ?";
PreparedStatement preparedStatement = null;
ResultSet set = null;
ArrayList<User> list = new ArrayList<>();//创建ArrayList 对象,存放user对象
//3. 创建PreparedStatement 对象
try {
connection = JDBCUtilsByDruid.getConnection();
System.out.println(connection.getClass());//运行类型com.alibaba.druid.pool.DruidPooledConnection
preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1, 1);//给?号赋值
//执行, 得到结果集
set = preparedStatement.executeQuery();
//遍历该结果集
while (set.next()) {
int id = set.getInt("id");
String name = set.getString("name");//getName()
String password = set.getString("password");//getSex()
Date birthday = set.getDate("birthday");
//把得到的resultset 的记录,封装到User 对象,放入到list 集合
list.add(new User(id, name, password, birthday));
}
System.out.println("list集合数据=" + list);
} catch (SQLException e) {
e.printStackTrace();
} finally {
//关闭资源
JDBCUtilsByDruid.close(set, preparedStatement, connection);
}
//因为ArrayList 和connection 没有任何关联,所以该集合可以复用.
for (User user : list) {
System.out.println("id=" + user.getId() + "\t" + "name=" + user.getName());
}
}
}
User.java
package com.jwt.jdbc.datasource;
import java.util.Date;
public class User { //JavaBean,POJO,Domain
private Integer id;//使用包装类原因后面说
private String name;
private String password;
private Date birthday;
public User() {
}
public User(Integer id, String name, String password, Date birthday) {
this.id = id;
this.name = name;
this.password = password;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "\nUser{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
commons- dbutils 是 Apache 组织提供的一个开源JDBC工具类库,它是对JDBC的封装,使用dbutils能极大简化jdbc编码的工作量。
DbUtils类
ArrayHandler: 把结果集中的第一行数据转成对象数组。 ArrayListHandler:把结果集中的每一行数据都转成一个数组, 再存放到List中。 BeanHandler:将结果集中的第一行数据封装到一个对应的JavaBean实例中。 BeanListHandler:将结果集中的每一行数据都封装到一个对应的JavaBean实例中,存放到List里。 ColumnListHandler:将结果集中某一列的数据存放到List中。 KeyedHandler(name): 将结果集中的每行数据都封装到Map里, 再把这些map再存到一个map里,其key为指定的key。 MapHandler:将结果集中的第一行数据封装到一个Map里,key是列名,value就是对应的值。 MapListHandler:将结果集中的每一行数据都封装到一个Map里,然后再存放到List
准备工作:使用DBUtils 类和接口, 先引入DBUtils 相关的 jar , 加入到本Project
1、使用apache-DBUtils 工具类+ druid 完成返回的结果是多行记录
package com.jwt.jdbc.datasource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_Use {
//使用apache-DBUtils 工具类+ druid 完成对表的crud 操作
@Test
public void testQueryMany() throws SQLException {
//1. 得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2. 创建QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3. 就可以执行相关的方法,返回ArrayList 结果集
String sql = "select * from user where id >= ?";
// 注意: sql 语句也可以查询部分列
//String sql = "select id, name from user where id >= ?";
// 老韩解读
//(1) query 方法就是执行sql 语句,得到resultset ---封装到--> ArrayList 集合中,再返回集合
//(2) connection: 连接
//(3) sql : 执行的sql 语句
//(4) new BeanListHandler<>(User.class): 在将resultset -> User 对象-> 封装到ArrayList
// 底层使用反射机制去获取User 类的属性,然后进行封装
//(5) 1 就是给sql 语句中的? 赋值,可以有多个值,因为是可变参数Object... params
//(6) 底层得到的resultset ,会在query 关闭, 关闭PreparedStatment
List<User> list = queryRunner.query(connection, sql, new BeanListHandler<>(User.class), 1);
System.out.println("list集合数据=" + list);
System.out.println("输出集合的信息");
for (User user : list) {
System.out.print(user);
}
//释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
}
2、使用apache-DBUtils 工具类+ druid 完成返回的结果是单行记录(单个对象)
package com.jwt.jdbc.datasource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_Use {
//演示apache-dbutils + druid 完成返回的结果是单行记录(单个对象)
@Test
public void testQuerySingle() throws SQLException {
//1. 得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2. 创建QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3. 就可以执行相关的方法,返回单个对象
String sql = "select * from user where id = ?";
// 因为我们返回的单行记录<--->单个对象, 使用的Hander 是BeanHandler
User user = queryRunner.query(connection, sql, new BeanHandler<>(User.class), 2);
System.out.println(user);
// 释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
}
3、使用apache-DBUtils 工具类+ druid 完成返回的结果是单行单列(object)
package com.jwt.jdbc.datasource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_Use {
//演示apache-dbutils + druid 完成查询结果是单行单列(object)
@Test
public void testScalar() throws SQLException {
//1. 得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2. 创建QueryRunner
QueryRunner queryRunner = new QueryRunner();
//3. 就可以执行相关的方法,返回单行单列, 返回的就是Object
String sql = "select name from user where id = ?";
//因为返回的是一个对象, 使用的handler 就是ScalarHandler
Object obj = queryRunner.query(connection, sql, new ScalarHandler(), 3);
System.out.println(obj);
// 释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
}
4、使用apache-DBUtils 工具类+ druid 完成dml (update, insert ,delete)
package com.jwt.jdbc.datasource;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import org.junit.Test;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_Use {
//演示apache-dbutils + druid 完成dml (update, insert ,delete)
@Test
public void testDML() throws SQLException {
//1. 得到连接(druid)
Connection connection = JDBCUtilsByDruid.getConnection();
//2. 使用DBUtils 类和接口, 先引入DBUtils 相关的jar , 加入到本Project
//3. 创建QueryRunner
QueryRunner queryRunner = new QueryRunner();
//4. 这里组织sql 完成update, insert delete
//String sql = "update user set name = ? where id = ?";
String sql = "insert into user values(null, ?, ?, ?)";//id为自增长
//String sql = "delete from user where id = ?";
//(1) 执行dml 操作是queryRunner.update()
//(2) 返回的值是受影响的行数(affected: 受影响)
//int affectedRow = queryRunner.update(connection,sql,Tom2,2);
int affectedRow = queryRunner.update(connection, sql, "jianjian", "789", "2000-10-10");
//int affectedRow = queryRunner.update(connection, sql, 3);
System.out.println(affectedRow > 0 ? "执行成功" : "执行没有影响到表");
// 释放资源
JDBCUtilsByDruid.close(null, null, connection);
}
}
int、double等在Java中都用包装类,因为mysql中的所有类型都可能是NULL,而Java只有引用数据类型才有 NULL值
apache dbutils+ Druid简化了JDBC开发,但还有不足:
DAO:data access objects 数据访问对象
文件列表
package com.jwt.dao_.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;
public class JDBCUtilsByDruid {
private static DataSource ds;
//在静态代码块完成ds 初始化
static {
Properties properties = new Properties();
try {
properties.load(new FileInputStream("src//druid.properties"));
ds = DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
//编写getConnection 方法
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
//关闭连接, 强调:在数据库连接池技术中,close 不是真的断掉连接
//而是把使用的Connection 对象放回连接池
public static void close(ResultSet resultSet, Statement statement, Connection connection) {
try {
if (resultSet != null) {
resultSet.close();
}
if (statement != null) {
statement.close();
}
if (connection != null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
package com.jwt.dao_.domain;
import java.util.Date;
public class User { //Javabean,POJO,Domain
private Integer id;
private String name;
private String password;
private Date birthday;
public User() {
}
public User(Integer id, String name, String password, Date birthday) {
this.id = id;
this.name = name;
this.password = password;
this.birthday = birthday;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
@Override
public String toString() {
return "\nUser{" +
"id=" + id +
", name='" + name + '\'' +
", password='" + password + '\'' +
", birthday=" + birthday +
'}';
}
}
package com.jwt.dao_.dao;
import com.jwt.dao_.utils.JDBCUtilsByDruid;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ScalarHandler;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class BasicDAO<T> { //泛型指定具体类型
private QueryRunner qr = new QueryRunner();
//开发通用的dml,针对任意表
public int update(String sql,Object... parameters){
Connection connection =null;
try {
connection = JDBCUtilsByDruid.getConnection();
int update = qr.update(connection,sql,parameters);
return update;
} catch (SQLException e) {
throw new RuntimeException(); //将编译异常转化为运行异常
} finally {
JDBCUtilsByDruid.close(null,null,connection);
}
}
/**
*
* @param sql sql 语句,可以有?
* @param clazz 传入一个类的Class 对象比如User.class
* @param parameters 传入? 的具体的值,可以是多个
* @return 根据User.class 返回对应的ArrayList 集合
*/
//查询多行结果的通用方法
public List<T> queryMulti(String sql,Class<T> clazz,Object... parameters){
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查询单行结果的通用方法
public T querySingle(String sql, Class<T> clazz, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
} catch (SQLException e) {
throw new RuntimeException(e); //将编译异常->运行异常,抛出
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
//查询单行单列的通用方法
public Object queryScalar(String sql, Object... parameters) {
Connection connection = null;
try {
connection = JDBCUtilsByDruid.getConnection();
return qr.query(connection, sql, new ScalarHandler<>(), parameters);
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUtilsByDruid.close(null, null, connection);
}
}
}
package com.jwt.dao_.dao;
import com.jwt.jdbc.datasource.User;
public class UserDAO extends BasicDAO<User> {
//1. 有BasicDAO 的方法
//2. 根据业务需求,可以编写特有的方法.
}
package com.jwt.dao_.test;
import com.jwt.dao_.dao.UserDAO;
import com.jwt.jdbc.datasource.User;
import org.junit.Test;
import java.util.List;
public class TestDAO {
////测试UserDAO 对user 表crud 操作
@Test
public void testUserDAO(){
UserDAO userDAO = new UserDAO();
//1.查询多行记录
List<User> users = userDAO.queryMulti("select * from user where id >=?", User.class, 1);
System.out.println("===查询结果===");
for (User user : users){
System.out.println(user);
}
//2.查询单行记录
User user = userDAO.querySingle("select * from user where id =?", User.class, 2);
System.out.println("===查询结果===");
System.out.println(user);
//3.查询单行单列
Object o = userDAO.queryScalar("select name from user where id =?", 3);
System.out.println("===查询结果===");
System.out.println(o);
//4.dml操作
int update = userDAO.update("insert into user values (null,?,?,?)", "pyj", "135", "2000-01-01");
System.out.println(update > 0 ? "执行成功":"执行没有影响表");
}
}
Button |
---|