数据库为两个,表结构都相同,现根据需要读取一个数据库表的数据到另一个数据库中,条件为数据库字段名与类文件的成员变量名一致,代码如下
private void getDATA(String cphm,String hpzl) throws Exception{
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
String JDriver=ContextUtil.getProperty().getProperty("jdbc.driverClassName");
String connectDB=ContextUtil.getProperty().getProperty("jdbc.url");
String user=ContextUtil.getProperty().getProperty("jdbc.username");
String pwd=ContextUtil.getProperty().getProperty("jdbc.password");
String sqlStr="select * from vehicle where cphm='"+cphm+"' and hpzl='"+hpzl+"' order by createtime desc";
try {
// 动态导入数据库的驱动
Class.forName(JDriver);
// 获取数据库链接
conn = DriverManager.getConnection(connectDB,user,pwd);
// 执行SQL语句
stmt = conn.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs=stmt.executeQuery(sqlStr);
//rs.first();
rs.last();
int rows=rs.getRow();
if(rows>0){
Class cls=Vehicle.class;
Field[] fields = cls.getDeclaredFields();
Object obj=(Object) cls.newInstance();
for (short j = 0; j < fields.length; j++) {
Field field = fields[j];
String fieldName = field.getName();
String setMethodName = "set"
+ fieldName.substring(0, 1).toUpperCase()
+ fieldName.substring(1);
Method setMethod=null;
if(field.getGenericType().toString().indexOf("Integer")>0){
setMethod = cls.getMethod(setMethodName,
new Class[] {Integer.class});
setMethod.invoke(obj, new Object[] {rs.getInt(fieldName)});
}else{
setMethod = cls.getMethod(setMethodName,
new Class[] {String.class});
setMethod.invoke(obj, new Object[] {rs.getString(fieldName)});
}
}
Vehicle vehicle=(Vehicle)obj;
vehicle.setId("");
//此处为Hibernate数据库持久层,把对象保存到数据库
commonService.saveObject(vehicle);
logger.info("从安检数据库取环保数据:"+vehicle.toString());
}
} catch (Exception e) {
logger.error("环保从安检数据库读取数据失败:"+ContextUtil.getTrace(e));
stmt.close();
conn.close();
throw e;
}
stmt.close();
conn.close();
}
注意:本文归作者所有,未经作者允许,不得转载