定义配置文件放在src目录下
#数据库连接路径
url=jdbc:mysql://localhost/day16
#登录用户名
username=root
#登录密码
password=root
#注册驱动
driver=com.mysql.jdbc.Driver
数据库连接工具类
package cn.itcast.utils;
import java.io.FileInputStream;
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 users;
private static String password;
private static String driver;
/*
* 文件的读取,只需要读取一次即可拿到这些值。使用静态代码块
* */
static{
//读取资源文件获取值
Properties pro = new Properties();
try {
//获取src路径下文件的方式-->ClassLoader
ClassLoader cl = JDBCUtils.class.getClassLoader();
URL res = cl.getResource("jdbc.properties");
String path = res.getPath();
pro.load(new FileInputStream(path));
url = pro.getProperty("url");
users = pro.getProperty("users");
password = pro.getProperty("password");
driver = pro.getProperty("driver");
// 注册驱动
Class.forName(driver);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/*
* 获取连接
* @return 连接对象
* */
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,users,password);
}
/*
* 释放资源
* */
public static void close(Statement stmt,Connection conn){
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close(Statement stmt, Connection conn, ResultSet rs){
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(rs !=null ){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}