建个ConnectionManager类来创立连接
package jdbcSimple;
import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import org.apache.log4j.Logger;
public class ConnectionManager {
private static final Logger logger = Logger
.getLogger(ConnectionManager.class);
//默认情况下
public synchronized static Connection getConnection() {
Connection conn = null;
String JdbcDriver = null;
String JdbcUrl = null;
String UserName = null;
String Password = null;
/* 开始读取配置文件中有关数据库的配置项 */
try {
JdbcDriver = Config.getProperty("driver");
JdbcUrl = Config.getProperty("url");
UserName = Config.getProperty("username");
Password = Config.getProperty("password");
} catch (Exception exception) {
logger.error("读取配置文件时出错:" + exception.toString());
return null;
}
try {
Class.forName(JdbcDriver);
conn = DriverManager.getConnection(JdbcUrl, UserName, Password);
conn.setAutoCommit(true);
} catch (Exception ex) {
ex.printStackTrace();
logger.error("应用系统连接数据库异常: " + ex.toString());
return null;
}
return conn;
}
public synchronized static Connection getConnection(String prefix) {
Connection conn = null;
String JdbcDriver = null;
String JdbcUrl = null;
String UserName = null;
String Password = null;
/* 开始读取配置文件中有关数据库的配置项 */
try {
JdbcDriver = Config.getProperty(prefix+"_driver");
JdbcUrl = Config.getProperty(prefix+"_url");
UserName = Config.getProperty(prefix+"_username");
Password = Config.getProperty(prefix+"_password");
} catch (Exception exception) {
logger.error("读取配置文件时出错:" + exception.toString());
return null;
}
try {
Class.forName(JdbcDriver);
conn = DriverManager.getConnection(JdbcUrl, UserName, Password);
conn.setAutoCommit(true);
} catch (Exception ex) {
ex.printStackTrace();
logger.error("应用系统连接数据库异常: " + ex.toString());
return null;
}
return conn;
}
public synchronized static void closeConnection(Connection conn) {
try {
if (conn != null)
conn.close();
} catch (Exception ex) {
logger.error("关闭Connection时异常: " + ex.toString());
} finally {
conn = null;
}
}
public synchronized static void closeStatement(Statement stmt) {
try {
if (stmt != null)
stmt.close();
} catch (Exception ex) {
logger.error("关闭Statement异常: " + ex.toString());
} finally {
stmt = null;
}
}
public synchronized static void closePreparedStatement(
PreparedStatement pstmt) {
try {
if (pstmt != null)
pstmt.close();
} catch (Exception ex) {
logger.error("关闭PreparedStatement异常: " + ex.toString());
} finally {
pstmt = null;
}
}
public synchronized static void closeResultSet(ResultSet rs) {
try {
if (rs != null)
rs.close();
} catch (Exception ex) {
logger.error("关闭ResultSet异常: " + ex.toString());
} finally {
rs = null;
}
}
public synchronized static void closeCallableStatement(
CallableStatement cstmt) {
try {
if (cstmt != null)
cstmt.close();
} catch (Exception ex) {
logger.error("关闭CallableStatement异常: " + ex.toString());
} finally {
cstmt = null;
}
}
}
回复 更多评论