jdbcytils工具包
用来获取数据库内容并释放资源
package com.zhongruan.de;
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
//引入properties文件
static {
try {
//创建properties集合类
Properties pro = new Properties();
//获取文件路径li
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc.properties");
String path = res.getPath();
pro.load(new FileReader(path));
//3获取数据
//3.1加载文件
//3.2获取数据
url = pro.getProperty("url");
user = pro.getProperty("user");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
//注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//为什么加静态: 因为这样就不需要创建对象来调用此方法,而是直接通过 类名.方法名()
public static Connection getConn() throws SQLException {
return DriverManager.getConnection(url, user, password);
}
public static void close(Statement stat, Connection conn){
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(ResultSet rs, Statement stat, Connection conn){
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
properties文件内容
url = com.mysql.jdbc.Driver
user = root
password = 123456
driver = com.mysql.jdbc.Driver