dao包
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.sxt.util.JdbcUtil;
/**
* 公共的Dao
*
* @author lujun
*
*/
public abstract class BaseDao<T> {
/**
* 公共查询方法1,返回实体对象的集合
* 参数1:要封装的实体类对应的class对象,用实体类.class
* 参数2:查询语句
* 参数3:给占位符赋值的数据
*
* @return
*/
public List<T> getList(Class<T> clazz, String sql, Object... params) {
List<T> list = new ArrayList<>();
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
// 给占位符?赋值
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
rs = stmt.executeQuery();
// 从结果集中获取所有的字段
ResultSetMetaData md = rs.getMetaData();
while (rs.next()) {
// 用反射创建一个对象
T obj = clazz.newInstance();
// 遍历所有的字段
for (int i = 1; i <= md.getColumnCount(); i++) {
// 获取当前列的列名,如果列有别名,就返回别名
String columnName = md.getColumnLabel(i).toLowerCase();
// 获取字段的值
Object columnValue = rs.getObject(columnName);
if (columnValue == null) {
// 结束本次循环
continue;
}
// 获取字段值的简短类型,例如String,Integer
String type = columnValue.getClass().getSimpleName();
// oracle会将number类型的字段解析成BigDecimal类型,mysql会将int和integer类型解析成int或Integer类型
switch (type) {
case "BigDecimal":
// 如果值里面有".",要当成小数来获取
if (columnValue.toString().contains(".")) {
columnValue = rs.getDouble(columnName);
} else {
columnValue = rs.getInt(columnName);
}
break;
case "int":
case "Integer":
columnValue = rs.getInt(columnName);
break;
}
// System.out.println("列名:" + columnName + ",字段值:" +
// columnValue + ",类型:" + type);
// 将获取到的字段的值封装到该字段对应的同名属性上
// 获取私有属性,根据属性名获取
Field field = clazz.getDeclaredField(columnName);
// 去除私有属性访问限制
field.setAccessible(true);
// 将字段值赋给对象的同名属性
field.set(obj, columnValue);
}
// System.out.println("*****************************************");
// 将对象添加到集合中
list.add(obj);
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeAll(rs, stmt, conn);
}
return list;
}
/**
* 公共查询方法2,返回1个实体对象
* 参数1:要封装的实体类对应的class对象,用实体类.class
* 参数2:查询语句
* 参数3:给占位符赋值的数据
*
* @return
*/
public T getBean(Class<T> clazz, String sql, Object... params) {
// 创建要返回的对象
T obj = null;
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = null;
ResultSet rs = null;
try {
stmt = conn.prepareStatement(sql);
// 给占位符?赋值
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
rs = stmt.executeQuery();
// 从结果集中获取所有的字段
ResultSetMetaData md = rs.getMetaData();
if (rs.next()) {
// 用反射创建对象
obj = clazz.newInstance();
// 遍历所有的字段
for (int i = 1; i <= md.getColumnCount(); i++) {
// 获取当前列的列名,如果列有别名,就返回别名
String columnName = md.getColumnLabel(i).toLowerCase();
// 获取字段的值
Object columnValue = rs.getObject(columnName);
if (columnValue == null) {
// 结束本次循环
continue;
}
// 获取字段值的简短类型,例如String,Integer
String type = columnValue.getClass().getSimpleName();
// oracle会将number类型的字段解析成BigDecimal类型,mysql会将int和integer类型解析成int或Integer类型
switch (type) {
case "BigDecimal":
// 如果值里面有".",要当成小数来获取
if (columnValue.toString().contains(".")) {
columnValue = rs.getDouble(columnName);
} else {
columnValue = rs.getInt(columnName);
}
break;
case "int":
case "Integer":
columnValue = rs.getInt(columnName);
break;
}
// System.out.println("列名:" + columnName + ",字段值:" +
// columnValue + ",类型:" + type);
// 将获取到的字段的值封装到该字段对应的同名属性上
// 获取私有属性,根据属性名获取
Field field = clazz.getDeclaredField(columnName);
// 去除私有属性访问限制
field.setAccessible(true);
// 将字段值赋给对象的同名属性
field.set(obj, columnValue);
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
JdbcUtil.closeAll(rs, stmt, conn);
}
return obj;
}
}
import java.util.List;
import com.sxt.entity.Dept;
/**
* 数据访问接口:操作数据库的dept表
*
* @author lujun
*
*/
public interface DeptDao {
// 添加
int insert(Dept dept);
// 修改
int update(Dept dept);
// 删除
int delete(Integer deptno);
// 全查询-查询所有记录
List<Dept> queryAll();
// 查询一条记录
Dept queryById(Integer deptno);
}
import java.util.List;
import com.sxt.entity.Account;
/**
* 操作账户表的dao接口
*
* @author lujun
*
*/
public interface AccountDao {
// 查询全部记录
List<Account> queryAll();
// 根据id查询一条记录
Account queryById(Integer aid);
}
dao 包的实现Impl
import java.util.List;
import com.sxt.dao.AccountDao;
import com.sxt.dao.BaseDao;
import com.sxt.entity.Account;
public class AccountDaoImpl extends BaseDao<Account> implements AccountDao {
@Override
public List<Account> queryAll() {
// TODO Auto-generated method stub
String sql = "select * from taccount";
List<Account> list = this.getList(Account.class, sql);
return list;
}
@Override
public Account queryById(Integer aid) {
// TODO Auto-generated method stub
String sql = "select * from taccount where aid=?";
Account account = this.getBean(Account.class, sql, aid);
return account;
}
}
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.sxt.dao.BaseDao;
import com.sxt.dao.DeptDao;
import com.sxt.entity.Dept;
import com.sxt.util.JdbcUtil;
/**
* 部门的Dao实现类,需要继承BaseDao,传入一个实体类进去
*
* @author lujun
*
*/
public class DeptDaoImpl extends BaseDao<Dept> implements DeptDao {
@Override
public int insert(Dept dept) {
String sql = "insert into dept values(?,?,?)";
// 从对象中通过getXxx()获取属性的值,再把值赋给?
int i = JdbcUtil.executeUpdate(sql, dept.getDeptno(), dept.getDname(), dept.getLoc());
return i;
}
@Override
public int update(Dept dept) {
// TODO Auto-generated method stub
String sql = "update dept set dname=?,loc=? where deptno=?";
int i = JdbcUtil.executeUpdate(sql, dept.getDname(), dept.getLoc(), dept.getDeptno());
return i;
}
@Override
public int delete(Integer deptno) {
// TODO Auto-generated method stub
String sql = "delete from dept where deptno=?";
int i = JdbcUtil.executeUpdate(sql, deptno);
return i;
}
@Override
public List<Dept> queryAll() {
// TODO Auto-generated method stub
String sql = "select * from dept";
// 调用getList方法,传入实体类名.class,查询语句,以及占位符的值
List<Dept> list = this.getList(Dept.class, sql);
return list;
}
@Override
public Dept queryById(Integer deptno) {
String sql = "select * from dept where deptno=?";
Dept dept = this.getBean(Dept.class, sql, deptno);
return dept;
}
/*
* public static void main(String[] args) { DeptDaoImpl deptdao=new
* DeptDaoImpl(); List<Dept> list = deptdao.getList(Dept.class,
* "select * from dept"); for (Dept dept : list) {
* System.out.println(dept); } }
*/
}
entity
/**
* 账户类
*
* @author lujun
*
*/
public class Account {
private Integer aid;
private String aname;
private Integer balance;
public Integer getAid() {
return aid;
}
public void setAid(Integer aid) {
this.aid = aid;
}
public String getAname() {
return aname;
}
public void setAname(String aname) {
this.aname = aname;
}
public Integer getBalance() {
return balance;
}
public void setBalance(Integer balance) {
this.balance = balance;
}
public Account(Integer aid, String aname, Integer balance) {
super();
this.aid = aid;
this.aname = aname;
this.balance = balance;
}
//无参构造方法
public Account() {
super();
// TODO Auto-generated constructor stub
}
@Override
public String toString() {
return "Account [aid=" + aid + ", aname=" + aname + ", balance=" + balance + "]";
}
}
/**
*
* 部门实体类:封装部门表的数据
*
* @author lujun
*
*/
public class Dept {
//提供3个私有属性和公有的getXxx()/setXxx(),属性名和字段名对应
private Integer deptno;
private String dname;
private String loc;
public Integer getDeptno() {
return deptno;
}
public void setDeptno(Integer deptno) {
this.deptno = deptno;
}
public String getDname() {
return dname;
}
public void setDname(String dname) {
this.dname = dname;
}
public String getLoc() {
return loc;
}
public void setLoc(String loc) {
this.loc = loc;
}
@Override
public String toString() {
return "Dept [deptno=" + deptno + ", dname=" + dname + ", loc=" + loc + "]";
}
}
util
import java.io.InputStream;
import java.io.Reader;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* jdbc操作数据库的工具类,封装通用的代码
*
* @author lujun
*
*/
public class JdbcUtil {
// 数据库驱动类
private static String driver;
// 数据库服务器的地址
private static String url;
// 连接服务器的用户名
private static String user;
// 连接服务器的用户密码
private static String password;
// 加载驱动只需要加载一次,可以放到静态代码块中
static {
try {
// 对db.properties文件的读取
Properties prop = new Properties();
// 加载文件,并转换为输入流,从流中读取数据
InputStream stream = JdbcUtil.class.getResourceAsStream("/db.properties");
prop.load(stream);
// 调用getProperty(String key),根据key获取相应的value
url = prop.getProperty("url");
user = prop.getProperty("user");
password = prop.getProperty("password");
driver = prop.getProperty("driver");
// 加载驱动
Class.forName(driver);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// 获取一个连接
public static Connection getConnection() {
Connection conn = null;
try {
conn = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
// 关闭资源
public static void closeAll(ResultSet rs, Statement stmt, Connection conn) {
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/*
* 通用增删改方法 参数1:要执行的DML语句(insert,update,delete语句)
* 参数2:给DML语句中的?赋的一组值,把占位符值统一放到可变参数中,可变参数可以当成数组用
* 返回值:执行增删改影响数据库的行数,如果成功,返回1,失败返回0
*/
public static int executeUpdate(String sql, Object... params) {
int count = 0;
// 创建连接
Connection conn = JdbcUtil.getConnection();
PreparedStatement stmt = null;
try {
// 创建预编译的statement
stmt = conn.prepareStatement(sql);
// 给占位符?赋值
for (int i = 0; i < params.length; i++) {
stmt.setObject(i + 1, params[i]);
}
count = stmt.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
// 关闭资源
JdbcUtil.closeAll(null, stmt, conn);
}
return count;
}
}
test
添加
import com.sxt.dao.DeptDao;
import com.sxt.dao.impl.DeptDaoImpl;
import com.sxt.entity.Dept;
/**
* 测试类--测试添加数据
* @author lujun
*
*/
public class Test1 {
public static void main(String[] args) {
//创建Dao实现类对象
DeptDao deptDao=new DeptDaoImpl();
Dept dept=new Dept();
dept.setDeptno(86);
dept.setDname("研发2部");
dept.setLoc("上海");
int i = deptDao.insert(dept) ;
if(i>0){
System.out.println("添加数据成功");
}else{
System.out.println("添加数据失败");
}
}
}
修改
import com.sxt.dao.DeptDao;
import com.sxt.dao.impl.DeptDaoImpl;
import com.sxt.entity.Dept;
/**
* 测试类--测试修改数据
* @author lujun
*
*/
public class Test2 {
public static void main(String[] args) {
//创建Dao实现类对象
DeptDao deptDao=new DeptDaoImpl();
Dept dept=new Dept();
dept.setDeptno(1);
dept.setDname("研发3部");
dept.setLoc("济南");
int i = deptDao.update(dept) ;
if(i>0){
System.out.println("修改数据成功");
}else{
System.out.println("修改数据失败");
}
}
}
查询
import java.util.List;
import com.sxt.dao.DeptDao;
import com.sxt.dao.impl.DeptDaoImpl;
import com.sxt.entity.Dept;
/**
* 测试类--测试查询所有数据
*
* @author lujun
*
*/
public class Test3 {
public static void main(String[] args) {
// 创建Dao实现类对象
DeptDao deptDao = new DeptDaoImpl();
List<Dept> list = deptDao.queryAll();
for (Dept dept : list) {
System.out.println(dept);
}
}
}
查询个别
import java.util.List;
import com.sxt.dao.AccountDao;
import com.sxt.dao.DeptDao;
import com.sxt.dao.impl.AccountDaoImpl;
import com.sxt.dao.impl.DeptDaoImpl;
import com.sxt.entity.Account;
import com.sxt.entity.Dept;
/**
* 测试类--测试查询所有数据
*
* @author lujun
*
*/
public class Test4 {
public static void main(String[] args) {
// 创建Dao实现类对象
AccountDao dao=new AccountDaoImpl();
/* List<Account> list = dao.queryAll();
for (Account account : list) {
System.out.println(account);
}*/
Account account = dao.queryById(2);
System.out.println(account);
}
}