1. 程式人生 > >單例模式獲取連線資料庫配置檔案

單例模式獲取連線資料庫配置檔案

//配置類(單例模式)
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.util.HashMap;
import java.util.Map;


public class Config {
private static Map<Integer, String> proMap = new HashMap<Integer, String>();


private static class MyConfig {
private static Config sql = new Config();
}
//讀取配置檔案,將配置檔案中的內容寫入集合
private Config() {
File f = new File("f:/work/SQL.ini");
FileReader fr = null;
BufferedReader br = null;
try {
fr = new FileReader(f);
br = new BufferedReader(fr);
for (int i = 0; i < 4; i++) {
int key = i;
String value = (String) (br.readLine());
proMap.put(key, value);
}
} catch (Exception e) {
} finally {
try {
fr.close();
br.close();
} catch (Exception e) {
}
}
}
public static Config getInsatnce(){
        return MyConfig.sql;
    }


public static Map<Integer, String> getPropMap() {
return proMap;
}

}

//資料庫驗證
import java.sql.*;
import java.util.Map;


class TestSQL {
public static void main(String[] args) {
String u = "aaab";
String p = "123448";
Connection cn = null;
PreparedStatement ps = null;
ResultSet rs = null;
//獲取配置資訊
Config t = Config.getInsatnce();
Map m = t.getPropMap();
String driver = (String)m.get(0);
String url = (String)m.get(1);
String username = (String)m.get(2);
String passwork = (String)m.get(3);

try {
Class.forName(driver);
cn = DriverManager.getConnection(url, username, passwork);
ps = cn.prepareStatement("select * from user where username=? and password=?");
ps.setString(1, u);
ps.setString(2, p);
rs = ps.executeQuery();
if (rs.next()) {
System.out.println("驗證成功");
} else {
System.out.println("驗證失敗");
}
}catch(Exception e) {
System.out.println(e);
}


}
}