3.ConnectionManager类[code=java]package dbutil;
import java.sql.*;
public final class ConnectionManager {
private static String driverClass = Env.driver;
private static String url = Env.url;
private static String userName = Env.userName;
private static String password = Env.password;
private static Driver driver=null;
private static Connection conn=null;
public static final Connection getConnection(){
try {
driver = new com.mysql.jdbc.Driver();
DriverManager.registerDriver(driver);
Class.forName(driverClass);
conn = DriverManager.getConnection(url,userName, password);
} catch (Exception e) {
e.printStackTrace();
}
return conn;
}
public static void closeDatabseObj(Connection connObj){
try {
if(connObj != null && !connObj.isClosed())
connObj.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeDatabseObj(Statement connObj){
try {
if(connObj != null)
connObj.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void closeDatabseObj(ResultSet connObj){
try {
if(connObj != null)
connObj.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}[/code]4.Env类[code=java]package dbutil;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public final class Env extends Properties {
private static final long serialVersionUID = 1L;
private static String path="db.properties";
public static String driver;
public static String url;
public static String userName;
public static String password;
private static Env env;
public Env(){}
public static void getEnv(){
if(env==null)
env = new Env();
}
static{
if(env==null)
getEnv();
try {
InputStream in = env.getClass().getResourceAsStream(path);
env.load(in);
in.close();
driver = env.getProperty("driver_class");
url = env.getProperty("db_url");
userName = env.getProperty("db_user");
password = env.getProperty("db_password");
} catch (IOException e) {
e.printStackTrace();
}
}
}[/code] |
|