Bean:
package com.czf.bean;
import java.sql.Date;
public class Order {
private int orderId;
private String orderName;
private Date orderDate;
public Order(int orderId, String orderName, Date orderDate) {
this.orderId = orderId;
this.orderName = orderName;
this.orderDate = orderDate;
}
public Order() {
}
public int getOrderId() {
return orderId;
}
public void setOrderId(int orderId) {
this.orderId = orderId;
}
public String getOrderName() {
return orderName;
}
public void setOrderName(String orderName) {
this.orderName = orderName;
}
public Date getOrderDate() {
return orderDate;
}
public void setOrderDate(Date orderDate) {
this.orderDate = orderDate;
}
@Override
public String toString() {
return "Order{" +
"orderId=" + orderId +
", orderName=‘" + orderName + ‘\‘‘ +
", orderDate=" + orderDate +
‘}‘;
}
}
针对Order的查询:
package com.czf.preparedstatement.crud;
import com.czf.bean.Order;
import com.czf.util.JDBCUtils;
import org.junit.Test;
import java.lang.reflect.Field;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
public class OrderForQuery {
@Test
public void orderForQueryTest(){
String sql = "select order_id orderId, order_name orderName, order_date orderDate from `order`";
List<Order> orders = orderForQuery(sql, null);
for (Order order : orders) {
System.out.println(order);
}
}
/**
* order表的通用查询
* 查询order表并返回一个Order对象列表(ORM)
* 针对表的字段名与类的属性名不相同的情况:
* 1.声明sql时,必须使用类的属性名来命名字段的别名
* 2.使用ResultSetMetaData时,需要使用getColumnLabel()来替换getColumnName(),获取列的别名
* 说明:如果sql中没有给字段别名,getColumnLabel()获取的就是列名,所以建议使用getColumnLabel()
* @param sql
* @param args
* @return Order对象列表
*/
public List<Order> orderForQuery(String sql, Object ...args){
List<Order> orders = new ArrayList<Order>();
Connection connection = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
//获得连接
connection = JDBCUtils.getConnection();
preparedStatement = connection.prepareStatement(sql);
//填充占位符
if (args != null) {
for (int i = 0; i < args.length; i++) {
preparedStatement.setObject(i + 1, args[i]);
}
}
//执行查询返回结果集
resultSet = preparedStatement.executeQuery();
//得到元数据
ResultSetMetaData metaData = resultSet.getMetaData();
//得到结果集列数
int columnCount = metaData.getColumnCount();
while(resultSet.next()){
Order order = new Order();
for (int i = 0; i < columnCount; i++) {
//反射得到Field
Field field = order.getClass().getDeclaredField(metaData.getColumnLabel(i + 1));
Object columnValue = resultSet.getObject(i + 1);
field.setAccessible(true);
field.set(order, columnValue);
}
orders.add(order);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
//关闭连接
JDBCUtils.closeResource(connection, preparedStatement, resultSet);
return orders;
}
}
}
控制台输出:
Order{orderId=1, orderName=‘AA‘, orderDate=2010-03-04}
Order{orderId=2, orderName=‘DD‘, orderDate=2000-02-01}
Order{orderId=4, orderName=‘GG‘, orderDate=1994-06-28}
待补充