在项目新建一个resources文件
再resources文件中创建一个文档命名为db.properties
在文件中配置jdbc连接数据库的四大要素
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/yunlian_db_test?useUnicode=true&characterEncoding=utf8
username=root
password=root
编写工具类DButil类
public class DButil {
private DButil(){}
static String url;
static String username;
static String password;
static String driver;
//从外面加载配置文件,通过静态代码快更加高效执行
static {
try {
Properties properties = new Properties();
FileReader fileReader = new FileReader("D:\\Projects\\jdbcDemo\\resources\\db.properties");
properties.load(fileReader);
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
Class.forName(driver);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
//调用这个connection方法就能直接读取配置文件的内容
public static Connection getConnection(){
try {
return DriverManager.getConnection(url,username,password);
} catch (SQLException throwables) {
throwables.printStackTrace();
}
return null;
}
//关流
public static void close(ResultSet resultSet,Statement statement,Connection connection){
if (resultSet != null){
try {
resultSet.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (statement!=null){
try {
statement.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if (connection!=null){
try {
connection.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
}