jdbc.properties文件:
user=root
password=123
url=jdbc:mysql://localhost:3306/test
driverClass=com.mysql.jdbc.Driver
public static Connection getConnection() throws Exception{
//1.读取配置文件中的4个基本信息
InputStream is = ClassLoader.getSystemClassLoader().getResourceAsStream("jdbc.properties");
Properties pros = new Properties();
pros.load(is);
String user = pros.getProperty("user");
String password = pros.getProperty("password");
String url = pros.getProperty("url");
String driverClass = pros.getProperty("driverClass");
//2.加载驱动
Class.forName(driverClass);
//3.获取连接
Connection conn = DriverManager.getConnection(url,user,password);
return conn;
}
public <T> List<T> getForList(Class<T> clazz, String sql, Object...args){
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
try{
conn = getConnection();
ps = conn.prepareStatement(sql);
for (int i = 0; i< args.length; i++){
ps.setObject(i + 1, args[i]);
}
rs = ps.executeQuery();
//获取结果集的元数据:ResultSetMetaData
ResultSetMetaData rsmd = rs.getMetaData();
//获取结果集中的列数
int columnCount = rsmd.getColumnCount();
//创建集合对象
ArrayList<T> list = new ArrayList<T>();
while(rs.next()){
T t = clazz.newInstance();
//处理结果集一行数据中的每一列
for(int i =0;i<columnCount;i++){
//获取列值
Object value = rs.getObject(i+1);
//获取每个列的列名:getColumnName()
//获取列的别名:getColumnLabel()
//String columnName = rsmd.getColumnName(i+1);
String columnName = rsmd.getColumnLabel(i+1);
//给cust对象指定的columnName属性,赋值为columValue
Field field = Customer.class.getDeclaredField(columnName);
field.setAccessible(true);
field.set(t, columValue);
}
list.add(t);
}
return cust;
}catch(Exception e){
e.printStackTrace();
}finally{
//关闭资源
}
return null;
}
String sql = "select id, name, email from customers where id < ?";
List<Customer> list = getForList(Customer.class, sql, 12);
list.forEach(System.out::println);
String sql1 = "select order_id orderId,order_name orderName form 'order';
List<Order> orderList = getForList(Order.class, sql1);
orderList.forEach(System.out::println);