1.写连接MySql数据配置文件:
文件名称:dbconfig.properties
DRIVER = com.mysql.jdbc.Driver
URL = jdbc:mysql://localhost:3306/javadb
USER = root
PASSWORD = root
2.使用IO流形式加载:
static{
InputStream in = DataBase.class.getClassLoader().getResourceAsStream("dbconfig.properties");
Properties p = new Properties();
try {
p.load(in);
Class.forName((String) p.get("DRIVER"));
URL = (String) p.get("URL");
USER = (String) p.get("USER");
PASSWORD = (String) p.get("PASSWORD");
} catch (Exception e) {
e.printStackTrace();
}
}
-连接:
public static Connection getConn() throws SQLException {
Connection connection = DriverManager.getConnection(URL,USER,PASSWORD);
return connection;
}
-关闭:
public static void close(Connection conn, Statement st, ResultSet re){
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(st!=null) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if(re!=null) {
re.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}