JDBC三层架构设计、Apache的DBUtils使用方法
1. JDBC 三层架构设计思想
2. Apache 的 DBUtils 使用方法
Commons DbUtils 是Apache组织提供的一个对JDBC进行简单封装的开源工具类库,使用它能勾简化JDBC应用程序的开发!同时,不会影响程序的性能。
DbUtils是Java编程中数据库操作实用小工具,小巧、简单、实用。
对于数据表的查询操作,可以吧结果转换为List、Array、Set等集合。
便于操作对于数据表的DML操作,也变得很简单(只需要写SQL语句)。
ResultSetHandler 接口:转换类型接口
BeanHandler 类:实现类,把一条记录转换成对象
BeanListHandler 类:实现类,把多条记录转换成List集合。
ScalarHandler 类:实现类,适合获取一行一列的数据。
QueryRunner:执行sql语句的类
增、删、改:update();
查询:query();
使用步骤:
① jar包:mysql-connector-java-5.1.25-bin.jar
② jar包:druid-1.1.5.jar
③ jar包:commons-dbutils-1.6.jar
④ database.properties配置文件
3. 代码示例
DBUtils.java 和 UserDaoImpl:
/**
* 连接池工具类
*/
public class DBUtils {
private static DruidDataSource dataSource;
static {
Properties properties = new Properties();
InputStream is = DBUtils.class.getResourceAsStream("/database.properties");
try {
properties.load(is);
dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
} catch (Exception e) {
e.printStackTrace();
}
}
// 返回一个数据源
public static DataSource getDataSource() {
return dataSource;
}
// 开启事务
public static void begin() {
try {
getDataSource().getConnection().setAutoCommit(false);
} catch (SQLException e) {
e.printStackTrace();
}
}
// 提交事务
public static void commit() {
try {
getDataSource().getConnection().commit();
} catch (SQLException e) {
e.printStackTrace();
}
}
// 回滚事务
public static void rollback() {
try {
getDataSource().getConnection().rollback();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public class UserDaoImpl implements UserDao {
//1.创建QueryRunner对象,并传递一个数据源对象
private QueryRunner queryRunner = new QueryRunner(DBUtils.getDataSource());
@Override
public int insert(User user) {
Object[] params={user.getId(),user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getAddress()};
try {
return queryRunner.update("insert into user (id,username,password,sex,email,address) values(?,?,?,?,?,?)",params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int update(User user) {
Object[] params={user.getUsername(),user.getPassword(),user.getSex(),user.getEmail(),user.getAddress(),user.getId()};
try {
return queryRunner.update("update user set username=?,password=?,sex=?,email=?,address=? where id = ?",params);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public int delete(int id) {
try {
return queryRunner.update("delete from user where id = ?",id);
} catch (SQLException e) {
e.printStackTrace();
}
return 0;
}
@Override
public User select(int id) {
try {
//把查询到的记录封装成 指定对象
return queryRunner.query("select * from user where id = ?", new BeanHandler<User>(User.class), id);
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 查询所有
* @return
*/
@Override
public List<User> selectAll() {
try {
return queryRunner.query("select * from user;",new BeanListHandler<User>(User.class));
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
}