首先需要新建一个customer类,真这样方便在后面对数据库进行操作
import java.util.Date;
public class Customer {
private int id;
private String name;
private String email;
private Date birth;
public Customer() {
}
public Customer(int id,String name, String email, Date birth ) {
this.name = name;
this.email = email;
this.birth = birth;
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 getBirth() {
return birth;
}
public void setBirth(Date birth) {
this.birth = birth;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
@Override
public String toString() {
return "Customer{" +
"id=" + id +
", name='" + name + '\'' +
", email='" + email + '\'' +
", birth=" + birth +
'}';
}
}
需要考虑好输出的内容即toStrinig里面的内容,如果不查询name中的内容,那么里面就会输出为空,不利于我们对数据库进行操作。
import java.lang.reflect.Field;
import java.sql.*;
public class CustomerForQuery {
// 针对customer通用查找表
public Customer querForCustomers( String sql,Object...args) {
// 1.获取链接
Connection conn= null;
PreparedStatement ps = null;
try {
conn = jdbcUtils.getConnection();
// 预编译sql语句
ps = conn.prepareStatement(sql);
// 填充占位符
for (int i = 0; i < args.length; i++) {
ps.setObject(i+1,args[i]);
}
//4.执行操作
ResultSet rs = ps.executeQuery();
// 获取结果集的元数据: ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
// 通过 ResultSetMetaData来获取结果集中列数
int columnCount = rsmd.getColumnCount();
if(rs.next()){
Customer cust=new Customer();
for (int i = 0; i < columnCount; i++) {
// 获取每一列的列值
Object columnvalue = rs.getObject(i + 1);
// 获取每个列的列名
String columnName = rsmd.getColumnName(i+1);
// 给cust对象指定的columnName属性,赋值为columnValue,通过反射
Field field = Customer.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(cust,columnvalue);
}
return cust;
}
} catch (NoSuchFieldException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
// 资源关闭
jdbcUtils.closeRescource(conn,ps);
}
return null;
}
}
虽然这种方法很好,但是apache里面的方法也可以用,但是对于学习嘛,大家还是应该知道原理是什么,这样就不害怕,别人跟你谈原理的时候
附一张结果图