//针对一个表,查询的通用操作
//传入查询语句。字段数可变参数
public Customer queryForCustomers(String sql, Object...args) {
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try {
conn = JDBCUtils.getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
ps.setObject(i + 1, args[i]);
}
//拿到结果集
rs = ps.executeQuery();
//获取结果集的 元数据
ResultSetMetaData rsmd = rs.getMetaData();
//通过 ResultSetMetaData 获取结果集中的列数
int columnCount = rsmd.getColumnCount();
if (rs.next()) {
//利用空参构造器造一个对象
Customer cust = new Customer();
//处理结果集一行数据中的每一个列
for (int i = 0; i < columnCount; i++) {
//获取这一列的列值
Object columvalue = rs.getObject(i + 1);
//获取每个列的列名
String columName = rsmd.getColumnName(i + 1);
//给 cust 对象指定的 columName 属性,复制为 columvalue ,通过反射
//调用运行时类的指定属性
Field field = Customer.class.getDeclaredField(columName);
field.setAccessible(true);
field.set(cust, columvalue);
}
return cust;//
}
} catch (Exception e) {
e.printStackTrace();
}finally{
JDBCUtils.closeResource2(conn, ps, rs);
}
return null;
}
上面代码中调用的 Customer 类:
/*
查询操作时,将数据封装在一个对象中
*/
public class Customer {
/*
ORM的编程思想:(object relational mapping)
一个数据表对应一个java类
表中的一条记录对应java类的一一个对象
表中的一个字段对应java类的一个属性
*/
private int id;
private String name;
private String email;
private Date birthday;
//空参构造器
public Customer() {
super();
}
//全参构造器
public Customer(int id, String name, String email, Date birthday) {
this.id = id;
this.name = name;
this.email = email;
this.birthday = birthday;
}
//get set 方法
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 String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
//toString 方法
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", birthday=" + birthday +
'}';
}
}
测试:
@Test//有错误,,没找到..sql语句中加了 birth 就会报 java.lang.NoSuchFieldException: birth
public void testQueryForCustomers(){
String sql = "select id,name,email,birth from customers where id=?";
Customer customer = queryForCustomers(sql, 1);
System.out.println(customer);
}