JDBC和连接池
大纲
- JDBC
- 连接数据库的方式
- JDBCUtils
- 事务
- 批处理事务
- 数据库连接池技术
- Apache–DBUtils
- BasicDAO
- 注意
具体案例
JDBC
需求:满足Java程序能对多个不同的数据库进行操作,而创建了一种接口,实现对数据库的规范
连接数据库的方式
1.方法1
先创建一个Driver对象,然后设置连接到的数据库的地址,然后创建一个properties对象,在里面设定好账户密码,然后通过driver的connect方法,创建出connect连接
public class jdbc01 {
public static void main(String[] args) throws SQLException {
// 前置工作,在项目下创建文件夹,然后将jar文件拷贝到该目录下,
// 然后将其加入到项目中
// 1.注册驱动
Driver driver = new Driver();
// 2.得到连接
// (1)jdbc:mysql://表示表示规定好的协议
// (2)localhost 应该是ip地址(这里是主机的ip地址)
// (3)3306表示MySQL监听的端口
// (4)test db 是指连接到MySQL的哪个数据库
// (5)本质上是进行socket连接
String url = "jdbc:mysql://localhost:3306/test01";
// 将用户名和密码封装到一个Properties对象中
Properties properties = new Properties();
// user和password是规定好的,后面的值根据实际情况
properties.setProperty("user","root");
properties.setProperty("password"," ");
Connection connect = driver.connect(url, properties);
// 3.执行sql语句
String sql = "insert into actor values(null,'刘德华','男','1970-11-11','110')";
// Statement 用于执行静态sql语句并返回生成的结果的对象
Statement statement = connect.createStatement();
int rows = statement.executeUpdate(sql);// 如果是dml语句,返回的就是影响到的行数
System.out.println(rows > 0? "成功":"失败");
//4.关闭连接
statement.close();
connect.close();
}
}
缺点:driver是第三方的,依赖性强,灵活性差
2.使用反射机制
public class jdbc02 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/test01";
Properties properties = new Properties();
properties.setProperty("user","root");
properties.setProperty("password","");
Connection connect = driver.connect(url, properties);
System.out.println(connect);
}
}
3.使用DriverManager替换Driver
这种方法具有更好的拓展性
public class jdbc03 {
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, SQLException {
Class<?> aClass = Class.forName("com.mysql.jdbc.Driver");
Driver driver = (Driver) aClass.newInstance();
String url = "jdbc:mysql://localhost:3306/test01";
String user = "root";
String password = "";
// 也可以还是使用properties来存储账户和密码,最后在DriverManager的getConnection方法里传入url和properties;
DriverManager.registerDriver(driver);
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
4.自动注册,简化操作(推荐使用)
在反射时,完成了类的加载,在静态代码块里实现了自动注册
public class jdbc04 {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
Class.forName("com.mysql.jdbc.Driver");// 可以不写
String url = "jdbc:mysql://localhost:3306/test01";
String user = "root";
String password = "";
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
5.使用配置文件(最推荐)
在4方法的基础上,使用配置文件来存储账户和密码,更加的灵活
下面是配置文件的格式(?rewriteBatchedStatements=true是为了批处理)
user=root
password=666
url=jdbc:mysql://localhost:3306/test01?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
public class jdbc05 {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
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("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println(connection);
}
}
执行sql语句
实际开发中,基本不使用statement,因为它不能预防sql注入
所以使用preparedStarement来防止sql的注入
使用这个类的好处
public class PreparedStatement {
public static void main(String[] args) throws IOException, ClassNotFoundException, SQLException {
Scanner myScanner = new Scanner(System.in);
System.out.println("请输入账号");
String account = myScanner.nextLine();
System.out.println("请输入密码");
String pwd = myScanner.nextLine();
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("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, user, password);
String sqlSelect = " select name,pwd from admin where name =? and pwd =?";
java.sql.PreparedStatement preparedStatement = connection.prepareStatement(sqlSelect);
// 赋值
preparedStatement.setString(1,account);
preparedStatement.setString(2,pwd);
ResultSet resultSet = preparedStatement.executeQuery();
// 得到一个查询到resultSet集
if (resultSet.next()){
System.out.println("恭喜,登录成功");
}else {
System.out.println("对不起,登录失败");
}
resultSet.close();
preparedStatement.close();
connection.close();
}
}
JDBCUtils
把JDBC的连接数据库操作,和关闭资源,封装到一个工具类中
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);
}
}
}
德鲁伊版本
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 JDBCUtilsNew {
// 使用druid来制作工具类,返回连接
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) {
throw new RuntimeException(e);
}
}
//编写getConnection方法,返回连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
// 关闭连接的方法,在数据库连接池技术中,close不是真的断掉连接
// 而是把使用的Connection对象返回连接池
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);
}
}
}
事务(Java中使用)
public class Transaction_ {
//没有使用事务.
@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(); // 执行第3条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(); // 执行第3条sql
//这里提交事务
connection.commit();
} catch (SQLException e) {
//这里我们可以进行回滚,即撤销执行的SQL
//默认回滚到事务开始的状态.
System.out.println("执行发生了异常,撤销执行的sql");
try {
connection.rollback();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
e.printStackTrace();
} finally {
//关闭资源
JDBCUtils.close(null, preparedStatement, connection);
}
}
}
批处理事务
请注意要在properties的数据库连接的地址后加上
?rewriteBatchedStatements=true这条语句,才能进行批处理
user=root
password=666
url=jdbc:mysql://localhost:3306/test01?rewriteBatchedStatements=true
driver=com.mysql.jdbc.Driver
下面是代码实例
public class Batch {
public void batch() throws SQLException {
// 调用自己定义的工具类返回connection
Connection connection = JDBCUtils.getConnection();
String sql = "insert into admin2 values(null,?,?)";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
System.out.println("开始执行");
long start = System.currentTimeMillis();
for (int i = 0; i < 5000; i++) {
preparedStatement.setString(1,"jack" + i);
preparedStatement.setString(2,"123");
// 将sql语句加入到批处理包中
preparedStatement.addBatch();
// 当有1000条记录时,再批量执行
if ((i + 1) % 1000 == 0){
preparedStatement.executeBatch();
// 清空一把,批处理包的语句
preparedStatement.clearBatch();
}
}
long end = System.currentTimeMillis();
System.out.println(end - start);
}
}
数据库连接池技术
传统连接到弊端
数据库连接池技术的原理和与传统对比
与原理的连接的方式不同,采用数据库连接池技术,可以避免重复的进行连接的创建和关闭,而是在一个设置好的连接池存储已经创建好的连接,而当我们使用或者不使用,只需要对连接池的connection进行引用的处理
,并且可以控制连接的数量
数据库连接池的种类
C3P0
下面是两种连接方式(注意都要引入c3p0-0.9.1.2.jar,并且添加到库)
第一种:获得配置文件,把配置文件里面的东西拿出来后,设置comboPooledDataSource里的数据,最后再创建连接
第二种:先导入c3p0-config.xml文件,再在创建comboPooledDataSource时,直接传入数据源的名称,之后再创建连接
public class C3P0_1 {
// 方式1:相关参数,在程序中指定user,url,password等
@Test
public void testC3P0_1() throws IOException, PropertyVetoException, SQLException {
// 1.创建一个数据源对象
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource();
// 2.通过配置文件获得相关信息
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.setUser(user);
comboPooledDataSource.setJdbcUrl(url);
comboPooledDataSource.setPassword(password);
//设置初始化连接数
comboPooledDataSource.setInitialPoolSize(10);
//设置最大连接数
comboPooledDataSource.setMaxPoolSize(50);
//进行连接()
Connection connection = comboPooledDataSource.getConnection();
System.out.println("连接成功");
connection.close();
}
// 方式2,使用配置文件模板来完成
// 1. 将C3P0 提供的 c3p0-config.xml 拷贝到src目录下
// 2. 该文件指定了连接数据库的相关参数
@Test
public void testC3P0_2 () throws SQLException {
// 指定的数据源的名称
ComboPooledDataSource comboPooledDataSource = new ComboPooledDataSource("myDataResource");
Connection connection = comboPooledDataSource.getConnection();
connection.close();
System.out.println("连接成功");
}
}
Druid
把druid-1.1.10.jar拷贝到一个包下,注意添加到库,先获取配置文件后,然后调用DruidDataSourceFactory的静态createDataSource方法创建一个DataSource对象后,再dataSource.getConnection();方法创建连接
public class Druid_1 {
@Test
public void testDruid() throws Exception {
// 1. 加入 Druid jar包,记得添加到库
// 2. 加入 配置文件,将其拷贝到src文件目录下
// 3. 创建Properties对象,读取配置文件
Properties properties = new Properties();
properties.load(new FileInputStream("src\\druid.properties"));
// 4. 创建一个指定参数的数据库连接池Druid连接池
DataSource dataSource = DruidDataSourceFactory.createDataSource(properties);
Connection connection = dataSource.getConnection();
System.out.println("连接池");
connection.close();
}
}
Apache–DBUtils
对于我们创建的连接Connection,查询得到ResultSet,如果想要继续使用ResultSet,那Connection连接是不能断开的,此外,ResultSet还有方法返回信息不明确,不能复用等缺点
为此,我们使用Apache–DBUtils来进行处理
注意:引入commons-dbutils-1.3.jar包到一个包下后,记得把它添加入库
下面是数据库的数据类型与Javabean的数据类型的对应表
使用Apeach-Dbutils操作(增删改查)
如下:
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 test.jdbc.JDBCUtilsDruid;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
public class DBUtils_01 {
//Apache--DBUtils 工具类 + Druid 完成对对象的crud操作
@Test//(存储多条记录)
public void testQueryMany() throws SQLException {
// 1.得到连接(Druid)
Connection connection = JDBCUtilsDruid.getConnection();
// 2.使用DBUtils类和接口,先引入DBUtils相关的jar文件后,把它加入到项目
// 3.创建 QueryRunner
QueryRunner queryRunner = new QueryRunner();
// 4.就可以执行相关的方法,返回Arraylist结果集
String sql = "select * from actor where id >= ?";
// (1) query 方法是执行sql语句,得到resultSet---封装到--->ArrayList 集合中
// (2) 返回集合
// (3) connection:连接
// (4) sql:执行的sql语句
// (5) new BeanHandler<>(Actor.class):在将resultSet -> Actor对象 -> 封装到 ArrayList
// 底层使用的是反射机制,获取我们指定的类进行封装,这个类是根据我们的数据库的表的信息来创建的
// (6) 1 就是给sql中的?赋值的,可以有多个值,因为是可变形参
// (7) public <T> T query(Connection conn, String sql, ResultSetHandler<T> rsh, Object... params) throws SQLException {}
// 注意!!!这里需要的集合,需要的是这个包下面的 import java.util.List;
List<Actor> list =
queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
System.out.println("输出集合的信息");
for (Actor actor :list ) {
System.out.println(actor);
}
// 释放资源
// 上面的操作得到的resultSet,PrepareStatement在query方法结束之后会自己关闭,关闭resultSet,PrepareStatement
// 我们自己就不用关闭resultSet了
JDBCUtilsDruid.close(null,null,connection);
}
@Test// (得到单行多列)
public void testQuerySingle() throws SQLException {
Connection connection = JDBCUtilsDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
String sql = "select * from actor where id = ? ";
Actor actor = queryRunner.query(connection, sql, new BeanHandler<>(Actor.class), 2);
// 因为我们返回的是单行记录<--->单个对象,使用Handler 是 BeanHandler 而不是 BeanListHandler
System.out.println(actor);
JDBCUtilsDruid.close(null,null,connection);
}
// 演示 Apache--DBUtils + Druid 完成查询结果是单行单列-返回的就是Object
@Test//(单行单列)
public void testScalar() throws SQLException {
Connection connection = JDBCUtilsDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
// 执行相关的方法,返回单行单列
String sql = "select name from actor where id = ? ";
Object query = queryRunner.query(connection, sql, new ScalarHandler(), 1);
System.out.println(query);
//释放资源
JDBCUtilsDruid.close(null,null,connection);
}
@Test
//演示apache-dbutils + druid 完成dml(update,insert,delete)
public void testDml() throws SQLException {
Connection connection = JDBCUtilsDruid.getConnection();
QueryRunner queryRunner = new QueryRunner();
String sql = "update actor set name = ? where id = ?";
//String sql = "insert into actor values(null,'林青霞','女','1996-10-10','11565')";
//String sal = "delete from actor where id = ?";
//(1) 执行 dml 的操作语句是queryRunner.update()
//(2) 该语句返回的是受影响的行数
int affectRow = queryRunner.update(connection, sql,"张三丰",1);
System.out.println(affectRow > 0 ? "执行成功":"没有对表产生影响");
//释放资源
JDBCUtilsDruid.close(null,null,connection);
}
}
BasicDAO
需求分析
数据库中的表对应Java里一个相应的类,也对应一个相应执行sql语句的DAO,而不同的表对应的不同的DAO可能有着共同的部分,所以我们把其抽象出来作为BasicDAO,下面是按照工具包,DAO,表,TestDAO四个来编写的示例,其中DAO实现了对对于的数据库的管理操作方法的封装
整个流程的代码实例:
工具包JDBCUtilsDruid
package end.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 JDBCUtilsDruid {
// 使用druid来制作工具类,返回连接
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) {
throw new RuntimeException(e);
}
}
//编写getConnection方法,返回连接
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
// 关闭连接的方法,在数据库连接池技术中,close不是真的断掉连接
// 而是把使用的Connection对象返回连接池
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);
}
}
}
表domain
Actor表
package end.domain;
import java.util.Date;
public class Actor {
private Integer id;
private String name;
private String sex;
private Date bornDate;
private String phone;
public Actor() {
// 一定要给一个无参构造器,保证反射需要
}
public Actor(Integer id, String name, String sex, Date bornDate, String phone) {
this.id = id;
this.name = name;
this.sex = sex;
this.bornDate = bornDate;
this.phone = phone;
}
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 getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBornDate() {
return bornDate;
}
public void setBornDate(Date bornDate) {
this.bornDate = bornDate;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
@Override
public String toString() {
return "Actor{" +
"id=" + id +
", name='" + name + '\'' +
", sex='" + sex + '\'' +
", bornDate=" + bornDate +
", phone='" + phone + '\'' +
'}';
}
}
Goods
package end.domain;
public class Goods {
private Integer id;
private String goods_name;
private Double price;
public Goods() {
}
public Goods(Integer id, String goods_name, Double price) {
this.id = id;
this.goods_name = goods_name;
this.price = price;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getGoods_name() {
return goods_name;
}
public void setGoods_name(String goods_name) {
this.goods_name = goods_name;
}
public Double getPrice() {
return price;
}
public void setPrice(Double price) {
this.price = price;
}
@Override
public String toString() {
return "Goods{" +
"id=" + id +
", goods_name='" + goods_name + '\'' +
", price=" + price +
'}';
}
}
dao
BasicDAO(父类DAO)
package end.dao;
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 test.jdbc.JDBCUtilsDruid;
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 = JDBCUtilsDruid.getConnection();
int update = qr.update(connection, sql, parameters);
return update;
}catch (SQLException e){
throw new RuntimeException(e);
}finally {
JDBCUtilsDruid.close(null,null,connection);
}
}
//返回多个对象(即查询的结果是多行的),针对任意表
/**
*
* @param sql sql 语句,可以有占位符?
* @param clazz 传入一个class对象
* @param parameters 传入?的具体的值
* @return 根据Class<T>返回对应的List集合
*/
public List<T> queryMultiply(String sql,Class<T> clazz,Object...parameters){
Connection connection = null;
try {
connection = JDBCUtilsDruid.getConnection();
List<T> query = qr.query(connection, sql, new BeanListHandler<T>(clazz), parameters);
return query;
}catch (SQLException e){
throw new RuntimeException();
}finally {
JDBCUtilsDruid.close(null,null,connection);
}
}
// 查询单行结果的方法
public T querySingle(String sql,Class<T> clazz,Object...parameters){
Connection connection = null;
try {
connection = JDBCUtilsDruid.getConnection();
T query = qr.query(connection, sql, new BeanHandler<T>(clazz), parameters);
return query;
}catch (SQLException e){
throw new RuntimeException();
}finally {
JDBCUtilsDruid.close(null,null,connection);
}
}
// 查询单行单列的方法
public Object queryScalar(String sql,Object...parameters){
Connection connection = null;
try {
connection = JDBCUtilsDruid.getConnection();
Object query = qr.query(connection, sql, new ScalarHandler(), parameters);
return query;
}catch (SQLException e){
throw new RuntimeException(e);
}finally {
JDBCUtilsDruid.close(null,null,connection);
}
}
}
ActorDAO
package end.dao;
import end.domain.Actor;
public class ActorDAO extends BasicDAO<Actor>{
// 1. 就有BasicDAO的方法
// 2. 可以根据业务需求有自己的特有的方法
}
GoodsDAO
package end.dao;
import end.domain.Goods;
public class GoodsDAO extends BasicDAO<Goods>{
}
测试类TestDAO
package end.test;
import end.dao.ActorDAO;
import end.dao.GoodsDAO;
import end.domain.Actor;
import end.domain.Goods;
import org.junit.Test;
import java.util.List;
public class TestDAO {
@Test
//测试ActorDAO对actor表的操作
public void testActorDAO(){
ActorDAO actorDAO = new ActorDAO();
// 1. 查询
List<Actor> actors = actorDAO.queryMultiply("select * from actor where id >= ?", Actor.class, 1);
System.out.println("===查询结果===");
for (Actor actor : actors) {
System.out.println(actor);
}
// 2. 查询单行记录
Actor actor = actorDAO.querySingle("select * from actor where id = ?", Actor.class, 2);
System.out.println("=====查询单行结果=====");
System.out.println(actor);
// 3. 查询单行单列
Object object = actorDAO.queryScalar("select name from actor where id = ?", 3);
System.out.println("======查询单行单列的结果======");
System.out.println(object);
//4. dml操作 insert,update,delete
int update = actorDAO.update("insert into actor values(null,?,?,?,?)", "张无忌", "男", "2000-11-11", "999");
System.out.println(update > 0 ? "添加张无忌成功":"添加张无忌失败");
}
// 下面是对GoodsDAO与Goods的测试
@Test
public void testGoodsDAO(){
//创建
GoodsDAO goodsDAO = new GoodsDAO();
//进行查询操作各种
List<Goods> goods = goodsDAO.queryMultiply("select * from goods where id >= ?", Goods.class, 1);
System.out.println("=========查询goods结果==========");
for (Goods good : goods) {
System.out.println(good);
}
int update = goodsDAO.update("insert into goods values(null,?,?)", "真我", 1800);
System.out.println(update > 0 ? "执行添加真我成功":"执行失败");
Goods goods1 = goodsDAO.querySingle("select * from goods where id = ? ", Goods.class, 3);
System.out.println("======查询goods单行结果======");
System.out.println(goods1);
Object object = goodsDAO.queryScalar("select goods_name from goods where id = ?", 1);
System.out.println("=======输出单行单列查询goods结果======");
System.out.println(object);
}
}
注意
-
c3p0-config.xml配置文件放在src下拷贝(这个名字不要更改),自己定义的配置文件也应该放在src下
-
其余的MySQL的驱动jar包和连接池如C3P0的驱动jar包或druid的驱动jar包,应该放在单独的一个包下拷贝,记得添加到库
-
对于queryRuner.query()方法返回的结果集,需要是import java.util.List包下的,如果报错,则需要手动引进这个包
// 注意!!!这里需要的集合,需要的是这个包下面的 import java.util.List;
List<Actor> list =
queryRunner.query(connection, sql, new BeanListHandler<>(Actor.class), 1);
- 在实际开发中,我们创建domain与表的对应关系时,尽量字段名字和表的列名保持一致,如果在多表查询中,确实有两个相同的字段,那可以在sql语句中,完成用 as 当做别名