package cn.com.util.db;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
public class DBUtil {
private static Connection conn;
private static PreparedStatement pstm;
private static String driverClassName="com.mysql.jdbc.Driver";
private static final String url="jdbc:mysql://10.0.0.88:3306/daiqi?useUnicode=true&characterEncoding=GBK&useServerPrepStmts=false&rewriteBatchedStatements=true";
private static final String user="root";
private static final String password="yx123";
private static Logger log = Logger.getLogger(DBUtil.class);
static
{
PropertyConfigurator.configure(getProperties("/config/log4j.properties"));
}
static
{
try {
Class.forName(driverClassName);
} catch (ClassNotFoundException e) {
log.debug("加载驱动失败");
e.printStackTrace();
}
}
private DBUtil(){
}
/**
* 获取数据库连接
* @return
*/
public static Connection getConnction(){
try {
conn = DriverManager.getConnection(url, user, password);
conn.setAutoCommit(false);
} catch (SQLException e) {
log.debug("创建数据库连接失败");
e.printStackTrace();
}
return conn;
}
/**
* 获取数据库PreparedStatement
* @param sql
* @param params
* @return
*/
public static PreparedStatement getPstm(String sql,List<Object> params) {
try {
if(sql != null && !sql.equals("")){
if(params == null){
params = new ArrayList<Object>();
}
pstm = getConnction().prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
for (int i = 0; i < params.size(); i++) {
pstm.setObject(i+1, params.get(i));
}
pstm.execute();
}
} catch (SQLException e) {
log.debug("创建PreparedStatement失败");
e.printStackTrace();
}
return pstm;
}
/**
* 获取结果集
* @param pstm
* @return
* @throws SQLException
*/
public static ResultSet getRs(PreparedStatement pstm){
try {
return pstm.getResultSet();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
/**
* 获取更新的数量
* @return
* @throws SQLException
*/
public static Integer getCount(PreparedStatement pstm){
try {
return pstm.getUpdateCount();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return null;
}
/**
* 读取properties文件
*
* @param path
* @return Properties
*/
public static Properties getProperties(String path) {
Properties prop = new Properties();
InputStream in = null;
//获取url地址
String empUrl = path.replace("%20", " ");// 如果你的文件路径中包含空格,是必定会报错的
try {
in = DBUtil.class.getResourceAsStream(empUrl);
prop.load(in);
in.close();
} catch (Exception e) {
e.printStackTrace();
}
return prop;
}
}