自定义JDBC工具类
1.加载驱动
2.获取连接对象
3.关闭连接
public class JDBCUtils {
private static String url = null;
private static String user = null;
private static String password = null;
private static String driverClass = null;
private static InputStream in = null;
// 利用静态代码块的特征,在类文件加载到内存的时候,就会执行静态代码块里面的代码
static {
try {
// 1.读取配置文件信息,读取properties文件
Properties props = new Properties();
// 如果一个properties文件加载到内存中,需要借助IO流
in = new FileInputStream("./src/db.properties");
// 2.利用Properties里面的load方法加载文件
props.load(in);
// 3.可以通过properties类对象,获取到想要的数据
url = props.getProperty("url");
user = props.getProperty("user");
password = props.getProperty("password");
driverClass = props.getProperty("driver");
// 4.加载类文件
Class.forName(driverClass);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
System.out.println("加载驱动失败");
} finally {
// 关闭文件连接
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* 获取数据库连接的对象
*
* @return
*/
public static Connection getConnection() {
Connection con = null;
try {
con = DriverManager.getConnection(url, user, password);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return con;
}
/**
* 关闭数据库连接,释放statement
*
* @param conn 数据库连接对象
* @param stmt statement对象
*/
public static void close(Connection conn, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
/**
* 关闭数据库连接,释放statement和ResultSet
*
* @param conn 数据库连接对象
* @param stmt Statement对象
* @param rs 结果集对象
*/
public static void close(Connection conn, Statement stmt, ResultSet rs) {
try {
if (rs != null) {
rs.close();
}
if (stmt != null) {
stmt.close();
}
if (conn != null) {
conn.close();
}
} catch (SQLException e) {
e.printStackTrace();
throw new RuntimeException(e);
}
}
}
把连接数据库需要的信息都保存在一个文件中,这个文件是一个properties文件
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/myuser?useSSL=true
user=root
password=beijing