import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.log4j.Logger;
public class DBUtils {
static Logger logger=Logger.getLogger("dao");
static {
try {
//加载数据库驱动
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
logger.debug(e.getMessage());
}
}
/**
* 获取数据库连接对象
* @param ip
* @param port
* @param account
* @param pwd
* @return
*/
public static Connection getConn(String ip,String port,String account,String pwd) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://"+ip+":"+port+"/tecno_factory_imei?rewriteBatchedStatements=true&useUnicode=true&characterEncoding=utf-8", account,pwd);
} catch (SQLException e) {
logger.debug(e.getMessage());
}
return conn;
}
/**
* 获取数据库连接对象
* @param ip
* @param port
* @param account
* @param pwd
* @return
*/
public static Connection getConnDataBase(String ip,String port,String account,String pwd) {
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://"+ip+":"+port+"/", account,pwd);
} catch (SQLException e) {
logger.debug(e.getMessage());
}
return conn;
}
/**
* 获取预处理语句执行对象
* @param conn
* @param sql
* @return
*/
public static PreparedStatement getPreparedStatement(Connection conn,
String sql) {
PreparedStatement pstmt = null;
try {
pstmt = conn.prepareStatement(sql);
} catch (SQLException e) {
logger.debug(e.getMessage());
}
return pstmt;
}
/**
* 关闭连接数据库对象
* @param conn
* @param pstmt
* @param res
*/
public static void close(Connection conn, PreparedStatement pstmt, ResultSet res) {
close(res);
close(pstmt);
close(conn);
}
/**
* 关闭连接数据库对象
* @param conn
* @param pstmt
*/
public static void close(Connection conn, PreparedStatement pstmt){
close(pstmt);
close(conn);
}
/**
* 关闭预出来对象
* @param pstmt
*/
public static void close(PreparedStatement pstmt) {
if (pstmt != null) {
try {
pstmt.close();
} catch (SQLException e) {
logger.debug(e.getMessage());
}
pstmt = null;
}
}
/**
* 关闭结果集对象
* @param res
*/
public static void close(ResultSet res) {
if (res != null) {
try {
res.close();
} catch (SQLException e) {
logger.debug(e.getMessage());
}
res = null;
}
}
/**
* 关闭数据库连接对象
* @param conn
*/
public static void close(Connection conn) {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
logger.debug(e.getMessage());
}
conn = null;
}
}