MySQL数据库的连接和关闭

public class DButil {

public static Connection getConection(){
Connection conn = null;
try {
Properties ps = new Properties();
FileInputStream fis = new FileInputStream("config.properties");//自定义的文件,包含Driver,URL,Username,Password
ps.load(fis);//关联文件
fis.close();

String driver = ps.getProperty("driver");
String url = ps.getProperty("url");
String uname = ps.getProperty("user");
String paw = ps.getProperty("password");

Class.forName(driver);
conn = DriverManager.getConnection(url, uname, paw);
if(conn != null){
System.out.println("连接成功!");
}else{
System.out.println("连接不成功!");
}
} catch (Exception e) {
e.printStackTrace();
}
return conn;

}

public static void close(Connection conn, Statement st, ResultSet rs){
try {
if (rs != null || !rs.isClosed()) {
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
try {
if (st != null || !st.isClosed()) {
st.close();
}
} catch (SQLException e) {
e.printStackTrace();
}finally{
try {
if (conn != null || !conn.isClosed()) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}

}

我觉得这种的好用,因为如果rs关闭出错,下面依然会执行!欢迎各位大神指出问题

猜你喜欢

转载自blog.csdn.net/wxj123465/article/details/52767803