利用反射获取SQL数据库的对象

来源:互联网 发布:传经破解软件 编辑:程序博客网 时间:2024/05/16 01:19
import java.io.InputStream;
import java.lang.reflect.Field;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.util.ArrayList;
import java.util.List;
import java.util.Properties;


import org.junit.Test;


public class WildQuaryDemo {
//1.获取Connection
private Connection conn=null;
private PreparedStatement ps=null;
private ResultSet rs=null;

@Test
public Connection getConn() throws Exception{
InputStream is=this.getClass().getClassLoader().getResourceAsStream("jdbc.properties");
Properties property=new Properties();
property.load(is);
String driver=property.getProperty("jdbc.driverClassName");
String userName=property.getProperty("jdbc.username");
String password=property.getProperty("jdbc.password");
String url=property.getProperty("jdbc.url");
Class.forName(driver);
conn=DriverManager.getConnection(url, userName, password);
System.out.println(conn);
return conn;

}
//2.获取PreparedStatement,并给PreparedStatement赋值
public void getPrepareS(String sql,Object...args) throws Exception{
ps=conn.prepareCall(sql);
for(int i=0;i<args.length;i++){
ps.setObject(i+1, args[i]);
}


}
// 3.获取Resultset,ResultSetMetaData,
public List<Object> getRS(Class clazz) throws Exception, IllegalAccessException{
// 4.根据传入的类的类型,反射创建类的对象,并将对应的属性和值封装到对象里面使用自定义反射或者直接用Beanutils.setProperty封装。或者将属性和值加入到Map<String,Object>中去
rs=ps.executeQuery();
ResultSetMetaData rsmd=rs.getMetaData();
List<Object> listObj=new ArrayList<Object>();
while(rs.next()){
Object newobj=clazz.newInstance();
System.out.println("newobj"+newobj);
for(int i=0;i<rsmd.getColumnCount();i++){
Object columnValue=rs.getObject(i+1);
String columnLableName=rsmd.getColumnLabel(i+1);
Field fld=clazz.getDeclaredField(columnLableName);
fld.setAccessible(true);
fld.set(newobj, columnValue);
// 使用反射设定属性的值,因为BeanUtils这个类只能针对Bean类。有限制。
}
listObj.add(newobj);

}
System.out.println("listObj:"+listObj);
return listObj;
}
0 0
原创粉丝点击