DbUtil.class鏈接數據庫
public class DbUtil {
private static String className;
private static String url;
private static String pwd;
private static String users;
private static Properties prop = new Properties();
//靜態塊 在方法被調用之前就執行了
static {
InputStream is = DbUtil.class.getResourceAsStream("Config.properties");
try {
prop.load(is);
className = prop.getProperty("className").trim();
url = prop.getProperty("url").trim();
users = prop.getProperty("users").trim();
pwd = prop.getProperty("pwd").trim();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
Class.forName(className);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
Connection conn = DriverManager.getConnection(url, users, pwd);
System.out.println("連接成功!");
return conn;
}
public static void closeConnection(Connection conn) throws SQLException{
if(conn!=null){
conn.close();
}
}
public static void main(String []args) throws SQLException {
System.out.println(getConnection());
}
}
配置文件:Config.properties
className=oracle.jdbc.OracleDriver
url=jdbc:oracle:thin:@localhost:1521:XE
users=supermarket
pwd=0000