import java.sql.SQLException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import java.util.MissingResourceException;
public class DBConnection {
/** JDBC Driver */
private static String jdbc_driver = "";
/** JDBC URL */
private static String jdbc_url = "";
/** DB Login User */
private static String jdbc_user = "";
/** DB Login Password */
private static String jdbc_password = "";
private static Connection connection;
private static final String file = "init.properties"; // 配置文件
static{
refresh();
}
public static void refresh() { // 从配置文件中得到URL和Driver信息
try {
InputStream inputStream = DBConnection.class.getClassLoader()
.getResourceAsStream(file);
Properties properties = new Properties();
properties.load(inputStream);
jdbc_user = properties.getProperty("1`jdbc.user");
jdbc_password = properties.getProperty("jdbc.password");
jdbc_driver = properties.getProperty("jdbc.driver");
jdbc_url = properties.getProperty("jdbc.url");
setConnection();
} catch (MissingResourceException mre) {
processException(file);
} catch (FileNotFoundException fnf) {
processException(file);
} catch (IOException ioe) {
processException(file);
}
}
private static void processException(String fileName) {
System.out.println("Resource bundle /"" + fileName
+ "/" not found or is incomplete");
System.out.println("Default values for database access will be used");
}
public static void setConnection() {
try {
Class.forName(jdbc_driver);
connection = DriverManager.getConnection(jdbc_url,jdbc_user,jdbc_password);
connection.setAutoCommit(true);
}catch (ClassNotFoundException e) {
System.out.println("connect false reason:" + e.getMessage());
e.printStackTrace();
}catch (SQLException e) {
System.out.println("connect false reason:" + e.getMessage());
e.printStackTrace();
}
}
public static Connection getConnection() {
return connection;
}
}