- 编写配置文件
- 在src目录下创建config.properties配置文件
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/kd34
username=root
password=root
2.编写jdbc工具类
//1.私有化构造方法
private JDBCUtils() {
}
//2.声明所需要的配置变量
private static String driverClass;
private static String url;
private static String username;
private static String password;
private static Connection con;
//3.提供静态代码块。读取配置文件的信息为变量赋值,注册驱动
static {
try {
//读取配置文件的信息为变量赋值
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
Properties prop = new Properties();
prop.load(is);
driverClass = prop.getProperty("driverClass");
url = prop.getProperty("url");
username = prop.getProperty("username");
password = prop.getProperty("password");
//注册驱动
Class.forName(driverClass);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//4.提供获取数据库连接方法
public static Connection getConnection() {
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return con;
}
//5.提供释放资源的方法
public static void close(Connection con, Statement stmt, ResultSet rs) {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
if (rs != null) {
rs.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
public static void close(Connection con, Statement stmt) {
try {
if (stmt != null) {
stmt.close();
}
if (con != null) {
con.close();
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
3.使用JDBC工具类优化数据