使用配置文件写一个JDBCUntils关于连接和关闭的类
import java.io.IOException;
import java.io.Reader;
import java.sql.*;
import java.util.Properties;
public class JDBCUntil {
static Properties pros=null;
static {
pros=new Properties();
try {
pros.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("db.properties"));
} catch (IOException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
Class.forName(pros.getProperty("mysqlDriver"));
return DriverManager.getConnection(pros.getProperty("mysqlURL"),pros.getProperty("mysqlUser"),pros.getProperty("mysqlPwd"));
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static void close(Connection con){
if(con!=null){
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Statement ps,Connection conn){
try {
if(ps!=null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public static void close(ResultSet rs,Statement ps,Connection conn){
try {
if(rs!=null){
rs.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(ps!=null){
ps.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
try {
if(conn!=null){
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
配置文件发到Src下
db.properties
mysqlDriver=com.mysql.cj.jdbc.Driver
mysqlURL=jdbc\:mysql\://localhost\:3306/jdbc?serverTimezone=UTC
mysqlUser=root
mysqlPwd=123456