81,122
社区成员




package com.gzsoft.secondWeb.util;
import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;
/**
* 单例的模式
* @author lyp
*
*/
public class DB {
private static Connection conn=null;
private static String driver;
private static String connectionURL;
private static String username;
private static String password;
static{
Properties p=new Properties();
InputStream in=DB.class.getClassLoader().getResourceAsStream("connection.properties");
try {
p.load(in);
driver=p.getProperty("driver");
connectionURL=p.getProperty("connection_URL");
username=p.getProperty("username");
password=p.getProperty("password");
} catch (IOException e) {
}
}
public static Connection getConnetion(){
if(conn==null){
try {
Class.forName(driver).newInstance();
DriverManager.getConnection(connectionURL,username,password);
System.out.print("success to connect to database!");
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
System.out.println("can't find the Driver");
} catch (SQLException e) {
System.out.println("fail to connect to database!");
}
}
return conn;
}
public static void closeAll(ResultSet rs,PreparedStatement psmt,Connection conn){
if(rs!=null){
try {
rs.close();
rs=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(psmt!=null){
try {
psmt.close();
psmt=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if(conn!=null){
try {
conn.close();
conn=null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
System.out.println("driver:"+driver+" connURL:"+connectionURL+" username:"+username+" password:"+password);
getConnetion();
}
}