将setObject隐藏,用反射获取model里面的数据

/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package com.eshore.fileExport; import java.lang.reflect.Field;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List; import org.apache.commons.beanutils.BeanUtils; /**
* @author mercy
*
*/
public class Converter<T> { public static <T> T convert2Bean(ResultSet rs, Class<T> bean) throws Exception {
Field[] fields = bean.getDeclaredFields();
T obj = bean.newInstance();
for (Field field : fields) {
String pname = field.getName();
BeanUtils.setProperty(obj, pname, rs.getObject(pname));
} return obj != null ? obj : null;
} public static <T> List<T> convert2BeanList(ResultSet rs, Class<T> bean) throws Exception {
Field[] fields = bean.getDeclaredFields();
List<T> lists = new ArrayList<T>();
String pName="";
String sqlName="";
while (rs.next()) {
T obj = bean.newInstance();
for (Field field : fields) {
String newName=getUnderlineString(field.getName());
if(newName.contains("_")){
String f1=newName.substring(0,newName.indexOf("_"));
String f2=newName.substring(newName.indexOf("_"),newName.indexOf("_")+1);
String f3=newName.substring(newName.indexOf("_")+1,newName.length());
System.out.println("f1:"+f1+",f2:"+f2+",f3:"+f3);
sqlName=f1+f2+f3;
}
pName = field.getName();
BeanUtils.setProperty(obj, pName, rs.getObject(sqlName));
}
lists.add(obj);
}
return lists != null ? lists : null;
}
public static char upperOrLower(char c){
if(c <= 90 && c >= 65){
c += 32;
} else if(c <= 122 && c >= 97){
c -= 32;
}
return c;
}
public static boolean isUpper(char c){
if(c <= 90 && c >= 65){
return true;
} else if(c <= 122 && c >= 97){
return false;
}
return false;
}
//由payType转为pay_type
public static String getUnderlineString(String str){
StringBuilder strs=new StringBuilder();
for(int i=0;i<str.length();i++){
if(isUpper(str.charAt(i))){
strs.append("_").append(upperOrLower(str.charAt(i)));
}else{
strs.append(str.charAt(i));
}
}
return strs.toString();
} }

 引用:

//获取前一天的所有计费数据
public List<BillData> queryBillList(int start,int size){
logger.info("query data...");
String sqlStr=sqlQuery+tableName;
List<BillData> billList=new ArrayList<BillData>();
ResultSet rs=null;
if(start!=0||size!=0){
sqlStr=sqlStr+" limit ?,?";
rs=util.Query(sqlStr,start,size);
}else{
rs=util.Query(sqlStr,null);
}
try {
return rs != null ? Converter.convert2BeanList(rs, BillData.class) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
//logger.info("sql:{}",sqlStr);
/*try {
while(rs.next()){
BillData bill=new BillData();
int i=1;
bill.setBusinessNumber(String.valueOf(rs.getObject(i++)));
bill.setPayType(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setAreaCode(String.valueOf(rs.getObject(i++)));
bill.setCreateTime(Timestamp.valueOf(String.valueOf(rs.getObject(i++))));
bill.setProductId(String.valueOf(rs.getObject(i++)));
bill.setProductSpecCode(String.valueOf(rs.getObject(i++)));
bill.setProductName(String.valueOf(rs.getObject(i++)));
bill.setPrice(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setBookType(Integer.parseInt(String.valueOf(rs.getObject(i++))));
bill.setAccType(String.valueOf(rs.getObject(i++)));
bill.setDeleCode(String.valueOf(rs.getObject(i++)));
billList.add(bill);
}
} catch (SQLException e) {
e.printStackTrace();
}
return billList;*/
}

  

 如果还要再全一点的话就是把Conveter当成一个实现类,再写两个接口方法,并且加上数据库池。

DBHelper:

package dbhelper;

import java.io.PrintWriter;
import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;
import java.util.logging.Logger; import javax.sql.DataSource; import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList; import utils.XMLUtils; public class DbHelper implements DataSource { /**
* 用于暂时的存储数据库信息的Map
*/
private static Map<String, String> map = new HashMap<String, String>(); /*
* 既然是一个数据库连接池,就必须有许多的连接,所以需要使用一个集合类保存这些连接 (non-Javadoc)
*
* @see javax.sql.CommonDataSource#getLogWriter()
*/
public static LinkedList<Connection> connpool = new LinkedList<Connection>(); /**
* 通过XMLUtils实现对配置文件的信息读取,并实现DriverManager的使用
*
* @throws Exception
*/
static {
try {
Document document = XMLUtils.getDocument();
NodeList nodes = document.getElementsByTagName("database");
for (int i = 0; i < nodes.getLength(); i++) {
Element element = (Element) nodes.item(i);
switch (element.getAttribute("name")) {
case "mysql":
NodeList childs = element.getChildNodes();
for (int j = 0; j < childs.getLength(); j++) {
Node node = childs.item(j);
String nodename = node.getNodeName();
String nodevalue = node.getTextContent();
map.put(nodename, nodevalue);
}
break;
case "sqlserver":
break;
}
}
} catch (Exception e) {
// TODO: handle exception
} } /**
* 预先注册数据源 ,保证数据可以正常的获取,每次查询的时候先调用这个方法
*
* @throws Exception
*/
public static void register() throws Exception {
String DRIVER = map.get("driver");
String URL = map.get("url");
String USER = map.get("user");
String PASSWORD = map.get("password");
Integer DATABASE_CONNECTION_POOL_SIZE = Integer.valueOf(map.get("poolsize"));
// 预先 添加驱动信息
Class.forName(DRIVER); for (int index = 0; index < DATABASE_CONNECTION_POOL_SIZE; index++) {
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
connpool.add(conn);
}
} /**
* 释放数据库连接对象
*
* @param conn
* 给定的数据库连接对象
*/
public static void release(Connection conn) {
try {
if (conn != null) {
connpool.add(conn);
}
} catch (Exception e) {
throw new RuntimeException("释放数据库连接对象时出错! :\n" + e);
}
} /**
* 释放数据库连接对象以及数据库查询对象
*
* @param conn
* 数据库连接对象
* @param stmt
* 数据库查询语句
*/
public static void release(Connection conn, Statement stmt) { try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException("释放数据库查询对象Statement时出错! :\n" + e);
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} release(conn);
} public static void release(Connection conn, Statement stmt, ResultSet rs) { try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
throw new RuntimeException(" 关闭数据库结果集对象时出错!:\n" + e);
} finally {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException("释放数据库查询对象Statement时出错! :\n" + e);
} finally {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (Exception e) {
throw new RuntimeException(e);
}
} release(conn);
} /**
* 从数据库连接池中获取数据库连接对象,同时维护好池的内容实时更新
*/
@Override
public Connection getConnection() throws SQLException { if (connpool.size() <= 0) {
throw new RuntimeException("数据库忙,请待会再试试吧!");
}
// 需要注意的是,不能使用get方式(这个方法知识返回一个引用而已),
// 应该在获取的同时,删除掉这个链接,之后再还回来.现在注意是返还给数据库连接池!!!
Connection conn = connpool.removeFirst();
MyConnection myconn = new MyConnection(conn); // 从这里开始返回的就是一个数据库连接池对象的conn
return myconn;
} ///////////////////////////////////////////////////////////////////////// datasource接口的实现方法开始 @Override
public PrintWriter getLogWriter() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setLogWriter(PrintWriter out) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setLoginTimeout(int seconds) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getLoginTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
// TODO Auto-generated method stub
return null;
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public Connection getConnection(String username, String password) throws SQLException {
// TODO Auto-generated method stub
return null;
}
///////////////////////////////////////////////////////////////////////// datasource接口的实现方法结束 /**
* 包装设计模式实现流程: 1.创建一个类,实现与被增强对象相同的接口 2.将被增强对象当做自定义类的一个成员变量
* 3.定义一个构造方法,将被增强对象传递进去 4.增强想要增强的方法,进行覆盖即可 5.对于不想被增强的方法,调用被增强对象的方法进行处理即可
*
* @author mercy
*
*/ /////////////////////////////////////////////////////////////////////// 使用包装设计模式,增强close方法的自定义类开始
class MyConnection implements Connection { private Connection conn; public MyConnection(Connection conn) {
this.conn = conn;
} /**
* 自定义的包装设计模式类,增强close方法, 将数据库链接资源返还给数据库连接池,而不是数据库
*/
public void close() {
connpool.add(conn);
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return this.conn.unwrap(iface);
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return this.conn.isWrapperFor(iface);
} @Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement();
} @Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql);
} @Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql);
} @Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return this.conn.nativeSQL(sql);
} @Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub
this.conn.setAutoCommit(autoCommit);
} @Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getAutoCommit();
} @Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
this.conn.commit();
} @Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub
this.conn.rollback();
} @Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return this.conn.isClosed();
} @Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getMetaData();
} @Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub
this.conn.setReadOnly(readOnly);
} @Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return this.conn.isReadOnly();
} @Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub
this.conn.setCatalog(catalog);
} @Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getCatalog();
} @Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub
this.conn.setTransactionIsolation(level);
} @Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getTransactionIsolation();
} @Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getWarnings();
} @Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
this.conn.clearWarnings();
} @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement(resultSetType, resultSetConcurrency);
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency);
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency);
} @Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getTypeMap();
} @Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub
this.conn.setTypeMap(map);
} @Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub
this.conn.setHoldability(holdability);
} @Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getHoldability();
} @Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return this.conn.setSavepoint();
} @Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return this.conn.setSavepoint(name);
} @Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
this.conn.rollback(savepoint);
} @Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub
this.conn.releaseSavepoint(savepoint);
} @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStatement(resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,
int resultSetHoldability) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareCall(sql, resultSetType, resultSetConcurrency, resultSetHoldability);
} @Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, autoGeneratedKeys);
} @Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, columnIndexes);
} @Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
// TODO Auto-generated method stub
return this.conn.prepareStatement(sql, columnNames);
} @Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createClob();
} @Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createBlob();
} @Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createNClob();
} @Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return this.conn.createSQLXML();
} @Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return this.conn.isValid(timeout);
} @Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
// TODO Auto-generated method stub
this.conn.setClientInfo(name, value);
} @Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
// TODO Auto-generated method stub
this.conn.setClientInfo(properties);
} @Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return this.conn.getClientInfo(name);
} @Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getClientInfo();
} @Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createArrayOf(typeName, elements);
} @Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
// TODO Auto-generated method stub
return this.conn.createStruct(typeName, attributes);
} @Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub
this.conn.setSchema(schema);
} @Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getSchema();
} @Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub
this.conn.abort(executor);
} @Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
// TODO Auto-generated method stub
this.conn.setNetworkTimeout(executor, milliseconds);
} @Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return this.conn.getNetworkTimeout();
} }
///////////////////////////////////////////////////////////////////////////// 包装设计模式结束
}

  QueryRunner:

/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package dbhelper; import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.List; import handlers.BeanListHandler;
import handlers.Handler; /**
* 业务核心类,实现自动化处理
*
* 包括自动化的增删改查
*
* @author 郭瑞彪
*
*/
public class QueryRunner { /**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @param params
* 对应于SQL语句的参数描述
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> T query(Connection conn, String sql, Handler<T> handler, Object... params) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
ResultSet rs = ps.executeQuery();
return handler.handle(rs);
} /**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> T query(Connection conn, String sql, Handler<T> handler) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
return handler.handle(rs);
} /**
* 数据库查询,根据给定的查询条件 返回实例化之后的bean对象。此处对应于无参的处理方式
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @return 返回实例化Bean对象
* @throws Exception
*/
public <T> List<T> query(Connection conn, String sql, BeanListHandler<T> beanListHandler) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
return beanListHandler.handle(rs);
} /**
* 数据库查询,根据给定的查询条件 返回封装了实例化的Bean对象的集合
*
* @param conn
* 数据库连接对象
* @param sql
* 进行查询的sql语句
* @param handler
* 处理结果集的接口实现
* @param params
* 对应于SQL语句的参数描述
* @return 返回封装了实例化之后的bean集合
* @throws Exception
*/
public <T> List<T> query(Connection conn, String sql, BeanListHandler<T> beanListHandler, Object... params)
throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
/**
* fixed bug: 之前忘记了处理params对应于sql语句中的占位符表达了,所以可能导致sql语句未赋值的问题。现已解决。
*/
if (params != null) {
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
}
ResultSet rs = ps.executeQuery();
return beanListHandler.handle(rs);
} /**
* 根据给定的参数实现向数据库中给定SQL语句的update,delete,insert 操作
*
* @param conn
* 数据库连接对象,用户不必关心其释放问题,这里自动将其释放
* @param sql
* 数据库查询语句
* @param params
* 对应于SQL语句占位符的参数列表
* @throws Exception
*/
public void update(Connection conn, String sql, Object... params) throws Exception {
PreparedStatement ps = conn.prepareStatement(sql);
for (int i = 0; i < params.length; i++) {
ps.setObject((i + 1), params[i]);
}
ps.executeUpdate();
DbHelper.release(conn, ps);
} }

  BeanHandler

/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package handlers; import java.sql.ResultSet;
import java.sql.SQLException; import dbhelper.Conveter; /**
* @author mercy
*
*/
public class BeanHandler<T> implements Handler<T> { /**
* The Class of beans produced by this handler.
*/
private final Class<T> type; /**
* Creates a new instance of BeanHandler.
*
* @param type
* The Class that objects returned from <code>handle()</code> are
* created from.
*/
public BeanHandler(Class<T> type) {
this.type = type;
} /*
* (non-Javadoc)
*
* @see handlers.Handler#handle(java.sql.ResultSet)
*/
@Override
public T handle(ResultSet rs) {
try {
return rs.next() ? Conveter.convert2Bean(rs, this.type) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} }

BeanListHandler: 

/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package handlers; import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.List; import dbhelper.Conveter; /**
* @author mercy
*
*/
public class BeanListHandler<T> implements ListHandler<T> { /**
* The Class of beans produced by this handler.
*/
private final Class<T> type; /**
* Creates a new instance of BeanHandler.
*
* @param type
* The Class that objects returned from <code>handle()</code> are
* created from.
*/ public BeanListHandler(Class<T> type) {
this.type = type;
} /*
* (non-Javadoc)
*
* @see handlers.Handler#handle(java.sql.ResultSet)
*/
@Override
public List<T> handle(ResultSet rs) throws SQLException {
try {
return rs != null ? Conveter.convert2BeanList(rs, this.type) : null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
} }

 XMLUtils:

 

/**
* @Date 2016年7月19日
*
* @author Administrator
*/
package utils; import java.io.File; import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult; import org.w3c.dom.Document; /**
* 提供实现对db.cfg.xml文件的读和查找工作
*
* @author mercy
*
*/
public class XMLUtils { // all the utils methods are static
public static Document getDocument() throws Exception { DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = factory.newDocumentBuilder();
Document document = builder.parse(new File("src/db.cfg.xml"));
return document;
} public static void write2Xml(Document document) throws Exception { TransformerFactory factory = TransformerFactory.newInstance();
Transformer transformer = factory.newTransformer(); // wrapper the two arguments
DOMSource xmlSource = new DOMSource(document); StreamResult targetResult = new StreamResult(new File("src/db.cfg.xml")); transformer.transform(xmlSource, targetResult); } }

db.cfg.xml:

<?xml version="1.0" encoding="UTF-8" ?>
<project>
<database name="mysql">
<driver>com.mysql.jdbc.Driver</driver>
<url>jdbc:mysql://192.168.115.72:8066/charge?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull</url>
<user>root</user>
<password>mysql</password>
<poolsize>3</poolsize>
</database>
</project>

读取properties数据:

package com.eshore.fileExport;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class ReadSettingFileUtils {
private Logger logger=LoggerFactory.getLogger(this.getClass());
//private static final String fileName="D:/fileTest1/properties/fileSettings.properties";
//private static final String fileName="/home/billing/test/fileSettings.properties";
private static final String fileName="/home/ismp/write_charge/program/setting/fileSettings.properties";
private static final String projectFileName="/fileSettings.properties";
private static Properties properties = new Properties();
public Map<String, String> getFileContent(){
this.load();
Map<String, String> map = new HashMap<String, String>((Map) properties);
return map;
}
/**
* 从文件里面读取不到配置的话就读取项目路径下的配置
* @author mercy
*/
public void load() {
if (null != properties) {
InputStream in = null;
try {
/* 从文件路径获取配置文件 */
logger.debug("classpath not found filename!!");
in = new FileInputStream(fileName);
properties.load(in);
logger.info("load config file success!");
} catch (FileNotFoundException e) {
logger.warn(" server config file not found!");
in = this.getClass().getResourceAsStream(projectFileName);
try {
properties.load(in);
} catch (IOException e1) {
e1.printStackTrace();
} } catch (IOException e) {
logger.error("load config file error!", e);
} finally {
if (null != in) {
try {
in.close();
} catch (IOException e) {
logger.error("read config file error:", e);
}
}
}
}
}
}

  

MapRegister:  

package com.eshore.fileExport;

import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; public class MapRegister{
private Logger log=LoggerFactory.getLogger(this.getClass());
public static Map<String, String> map = new HashMap<String, String>();
public void init(){
map= new ReadSettingFileUtils().getFileContent();
for (Entry<String, String> entry : map.entrySet()) {
log.info("key:"+entry.getKey()+",value:"+entry.getValue());
}
}
public static Map<String, String> getMap() {
return map;
}
public static void setMap(Map<String, String> map) {
MapRegister.map = map;
}
}

propertis配置文件:  

 

##driver name
driver=com.mysql.jdbc.Driver
##database url
##acccount
#user=root
##password
#password=123456
##table name
url=jdbc:mysql://127.0.0.1:8066/charge?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
user=mycat
password=test
tableName=T_HB_DAY_FTP_MONITOR_DATA
##source file path
#ftpDir=/home/ismp/write_charge/program/data/file/
ftpDir=D:/fileTest1/old/
##bak file path
#localBakDir=/home/ismp/write_charge/program/data/bak/
localBakDir=D:/fileTest1/new/
fileName=ETE_0_100003_CEI015_2_L_yyyymmdd_000000_20_0_xxx.json
dataNum=50000

  

JDBC改进版的更多相关文章

  1. Java数据库连接技术——JDBC

    大家好,今天我们学习了Java如何连接数据库.之前学过.net语言的数据库操作,感觉就是一通百通,大同小异. JDBC是Java数据库连接技术的简称,提供连接各种常用数据库的能力. JDBC API ...

  2. 玩转spring boot——结合AngularJs和JDBC

    参考官方例子:http://spring.io/guides/gs/relational-data-access/ 一.项目准备 在建立mysql数据库后新建表“t_order” ; -- ----- ...

  3. [原创]java使用JDBC向MySQL数据库批次插入10W条数据测试效率

    使用JDBC连接MySQL数据库进行数据插入的时候,特别是大批量数据连续插入(100000),如何提高效率呢?在JDBC编程接口中Statement 有两个方法特别值得注意:通过使用addBatch( ...

  4. JDBC MySQL 多表关联查询查询

    public static void main(String[] args) throws Exception{ Class.forName("com.mysql.jdbc.Driver&q ...

  5. JDBC增加删除修改

    一.配置程序--让我们程序能找到数据库的驱动jar包 1.把.jar文件复制到项目中去,整合的时候方便. 2.在eclipse项目右击"构建路径"--"配置构建路径&qu ...

  6. JDBC简介

    jdbc连接数据库的四个对象 DriverManager  驱动类   DriverManager.registerDriver(new com.mysql.jdbc.Driver());不建议使用 ...

  7. JDBC Tutorials: Commit or Rollback transaction in finally block

    http://skeletoncoder.blogspot.com/2006/10/jdbc-tutorials-commit-or-rollback.html JDBC Tutorials: Com ...

  8. FineReport如何用JDBC连接阿里云ADS数据库

    在使用FineReport连接阿里云的ADS(AnalyticDB)数据库,很多时候在测试连接时就失败了.此时,该如何连接ADS数据库呢? 我们只需要手动将连接ads数据库需要使用到的jar放置到%F ...

  9. JDBC基础

    今天看了看JDBC(Java DataBase Connectivity)总结一下 关于JDBC 加载JDBC驱动 建立数据库连接 创建一个Statement或者PreparedStatement 获 ...

随机推荐

  1. 各大公司Java面试题超详细总结

    ThreadLocal(线程变量副本)Synchronized实现内存共享,ThreadLocal为每个线程维护一个本地变量.采用空间换时间,它用于线程间的数据隔离,为每一个使用该变量的线程提供一个副 ...

  2. MongoDB:通过mongodump【时间一致性】备份,快速创建secondary复制集节点——更精简的方式2

    该方式优点:快速通过mongodump初始化数据库,大大减少新的secondary节点从头开始初始化的风险:网络壅塞.oplog.rs过期.耗时太长等. 还原的关键:一致性mongodump备份 +  ...

  3. Android 内存

    memory usage of this progress under 15MB for 1GB RAM device Android内存机制分析下篇:分析APP内存使用情况http://mobile ...

  4. Java -- IO -- 目录

    操作文件的类 -- -- File File类的基本介绍 使用File类操作文件 范例 -- -- 列出指定目录的全部内容 RandomAccessFile类 使用RandomAccessFile类写 ...

  5. Go之继承的实现

    go的继承是使用匿名字段来实现的 package util //----------------Person---------------- type Person struct { Name str ...

  6. 【SVN】自动定时更新

    程序或脚本:"C:\Program Files\TortoiseSVN\bin\svn.exe" 参数:update E:\XXXXProjects\Code 参考:https:/ ...

  7. 使用 urllib 设置代理服务

    (1) 如果我们一直用同一个IP去请求同一个网站上的网页,久了之后可能会被该网站服务器屏蔽,因此我们可以使用代理IP来发起请求,代理实际上指的就是代理服务器(2) 当我们使用代理IP发起请求时,服务器 ...

  8. 编译poco-1.7.8

    运行build_vs140.cmd,运行之前可以修改一些参数,例如编译64位 buildwin 140 build shared both x64 nosamples notests devenv 修 ...

  9. AddChild

    using UnityEngine; using UnityEngine; using UnityEditor; using System.Collections; public class AddC ...

  10. mysql分组查询获取组内某字段最大的记录

    id sid cid 1 1 12 1 23 2 1 以sid分组,最后取cid最大的那一条,以上要取第2.3条 1 方法一: select * from (select * from table o ...