1.封装JDBC工具类
① 创建一个 com.util.db 包,新建一个db-config.properties的属性文件。
com.util.db
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=root
jdbc.server=com.mysql.jdbc.Driver
② 在 com.util.db 包中,新建一个DBUtils.java类。
DBUtils.java
package com.util.db;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;
public class DBUtils {
//数据库连接地址
public static String URL;
//用户名
public static String USERNAME;
//密码
public static String PASSWORD;
//MYSQL驱动类
public static String SERVER;
//加载属性资源
private static ResourceBundle rb = ResourceBundle.getBundle("com.util.db.db-config");
//私有化构造方法
private DBUtils(){}
//静态块加载驱动程序
static{
URL = rb.getString("jdbc.url");
USERNAME = rb.getString("jdbc.username");
PASSWORD = rb.getString("jdbc.password");
SERVER = rb.getString("jdbc.server");
try {
Class.forName(SERVER);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//定义一个获取数据库连接的方法
public static Connection getConnection(){
Connection conn = null;
try {
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
//关闭数据库
public static void close(ResultSet rs,Statement st,Connection conn){
try {
if(rs != null)rs.close();
if(st != null)st.close();
if(conn != null)conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
2.DAO设计模式实现增删改查
①在包 com.ldp.domain 中 创建一个Person类
Person.java
package com.ldp.domain;
public class Person {
private int id;
private String name;
private int age;
private String description;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Person(int id, String name, int age, String description) {
super();
this.id = id;
this.name = name;
this.age = age;
this.description = description;
}
public Person(String name, int age, String description) {
super();
this.name = name;
this.age = age;
this.description = description;
}
public Person() {
super();
}
@Override
public String toString() {
return "Person [id=" + id + ", name=" + name + ", age=" + age + ", description=" + description + "]";
}
}
②在包 com.ldp.dao 中创建一个接口类,定义增删改查的方法。
PersonDao.java
package com.ldp.dao;
import java.sql.SQLException;
import java.util.List;
import com.ldp.domain.Person;
public interface PersonDao {
//添加方法
public void add(Person p) throws SQLException;
//更新方法
public void update(Person p)throws SQLException;
//删除方法
public void delete(int id) throws SQLException;
//查找方法
public Person findById(int id)throws SQLException;
//查找所有
public List findAll() throws SQLException;
}
③在包 com.ldp.dao.impl 中定义一个实现类,实现增删改查的方法。
PersonDaoImpl.java
package com.ldp.dao.impl;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ldp.dao.PersonDao;
import com.ldp.domain.Person;
import com.util.db.DBUtils;
public class PersonDaoImpl implements PersonDao {
@Override
public void add(Person p) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql = "insert into person(name,age,description)values(?,?,?)";
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, p.getName());
ps.setInt(2, p.getAge());
ps.setString(3, p.getDescription());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.close(null, ps, conn);
}
}
@Override
public void update(Person p) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql = "update person set name = ?,age=?,description=? where id = ?";
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setString(1, p.getName());
ps.setInt(2, p.getAge());
ps.setString(3, p.getDescription());
ps.setInt(4, p.getId());
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.close(null, ps, conn);
}
}
@Override
public void delete(int id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
String sql = "delete from person where id = ?";
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
DBUtils.close(null, ps, conn);
}
}
@Override
public Person findById(int id) throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select name,age,description from person where id = ?";
Person person = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
ps.setInt(1, id);
rs = ps.executeQuery();
while(rs.next()){
person = new Person();
person.setId(id);
person.setName(rs.getString(1));
person.setAge(rs.getInt(2));
person.setDescription(rs.getString(3));
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.close(rs, ps, conn);
}
return person;
}
@Override
public List findAll() throws SQLException {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
String sql = "select id,name,age,description from person ";
List persons = new ArrayList();
Person person = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
rs = ps.executeQuery();
while(rs.next()){
person = new Person();
person.setId(rs.getInt(1));
person.setName(rs.getString(2));
person.setAge(rs.getInt(3));
person.setDescription(rs.getString(4));
persons.add(person);
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
DBUtils.close(rs, ps, conn);
}
return persons;
}
}
3.优化DAO设计模式实现增删改查
①在包 com.ldp.base 中,新建一个处理结果集的接口。
ResultSetHandler.java
package com.ldp.base;
import java.sql.ResultSet;
import java.sql.SQLException;
public interface ResultSetHandler {
public Object doHandler(ResultSet rs)throws SQLException;
}
②包 com.util.db 中,新建一个模板类,实现增删改查的功能。
JdbcTemplete.java
package com.util.db;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.ldp.base.ResultSetHandler;
public class JdbcTemplete {
/**
* 实现增删改的抽象
* @param sql
* @param args
*/
public int update(String sql,Object...args){
Connection conn = null;
PreparedStatement ps = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
if (args!=null) {
for(int i = 0; i < args.length;i++){
ps.setObject(i+1, args[i]);
}
}
return ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
return 0;
}finally {
DBUtils.close(null, ps, conn);
}
}
/**
* 实现查询操作
* @param sql
* @param handler
* @param args
* @return
*/
public Object query(String sql,ResultSetHandler handler,Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = DBUtils.getConnection();
ps = conn.prepareStatement(sql);
if (args!=null) {
for(int i = 0; i < args.length;i++){
ps.setObject(i+1, args[i]);
}
}
rs = ps.executeQuery();
return handler.doHandler(rs);
} catch (SQLException e) {
e.printStackTrace();
return null;
}finally{
DBUtils.close(rs, ps, conn);
}
}
}
③在包 com.ldp.dao.impl 中实现增删改查的方法。
PersonDaoImpl.java
package com.ldp.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.ldp.base.ResultSetHandler;
import com.ldp.dao.PersonDao;
import com.ldp.domain.Person;
import com.util.db.JdbcTemplete;
public class PersonDaoImpl implements PersonDao {
//模板属性
private JdbcTemplete jdbcTemplete;
public PersonDaoImpl() {
jdbcTemplete = new JdbcTemplete();
}
@Override
public void add(Person p) throws SQLException {
String sql = "insert into person(name,age,description)values(?,?,?)";
jdbcTemplete.update(sql, p.getName(),p.getAge(),p.getDescription());
}
@Override
public void update(Person p) throws SQLException {
String sql = "update person set name = ?,age=?,description=? where id = ?";
jdbcTemplete.update(sql, p.getName(),p.getAge(),p.getDescription(),p.getId());
}
@Override
public void delete(int id) throws SQLException {
String sql = "delete from person where id = ?";
jdbcTemplete.update(sql, id);
}
@Override
public Person findById(final int id) throws SQLException {
String sql = "select name,age,description from person where id = ?";
return (Person)jdbcTemplete.query(sql, new ResultSetHandler() {
@Override
public Object doHandler(ResultSet rs) throws SQLException {
Person p = null;
if (rs.next()) {
p = new Person();
p.setId(id);
p.setName(rs.getString(1));
p.setAge(rs.getInt(2));
p.setDescription(rs.getString(3));
}
return p;
}
}, id);
}
@SuppressWarnings("unchecked")
@Override
public List findAll() throws SQLException {
String sql = "select id,name,age,description from person ";
return (List)jdbcTemplete.query(sql, new ResultSetHandler() {
@Override
public Object doHandler(ResultSet rs) throws SQLException {
List persons = new ArrayList();
Person p = null;
while(rs.next()){
p = new Person();
p.setId(rs.getInt(1));
p.setName(rs.getString(2));
p.setAge(rs.getInt(3));
p.setDescription(rs.getString(4));
persons.add(p);
}
return persons;
}
});
}
}
4.方法的调用
public class Demo {
public static void main(String[] args) throws SQLException {
PersonDao pDao = new PersonDaoImpl();
Person p = new Person("小黑",25,"abc");
pDao.add(p);
}
}