首先
连接数据库的方法有很多种,这里选择一种我喜欢的方法,使用properties的配置文件
我使用的mysql的版本是8.0以上的 driver为com.mysql.cj.jdbc.Driver
以下的版本driver没cj
配置信息如下 类似键值对
user=root
password=iamsorry36
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/labbook09
接着
这里需要有一定io流的知识点
配置文件写好,需要读取
//读取文件
Properties properties = new Properties();
properties.load(new FileInputStream("src\\labbook09\\mysql_2.properties"));
然后
读取完了需要获取值
//获得相关属性
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
url = properties.getProperty("url");
将获取的相关属性放入DriverManager.getConnection(url,user,password)
这个时候就是拿到连接了
最后代码结果
import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;
public class Utils {
//静态定义相关属性
private static String user;
private static String password;
private static String url;
private static String driver;
//使用静态代码块去初始化
static {
try {
//读取文件
Properties properties = new Properties();
properties.load(new FileInputStream("src\\labbook09\\mysql_2.properties"));
//获得相关属性
user = properties.getProperty("user");
password = properties.getProperty("password");
driver = properties.getProperty("driver");
url = properties.getProperty("url");
} catch (IOException e) {
//把编写异常改为运行异常
throw new RuntimeException(e);
}
}
//获取连接
public static Connection getConnection(){
try {
Class.forName(driver);
return DriverManager.getConnection(url,user,password);
} catch (SQLException | ClassNotFoundException e) {
//把编写异常改为运行异常
throw new RuntimeException(e);
}
}
//关闭资源
/*
* 思路分析 需要关闭哪些内容
* resultset
* statement 或者 preparestatement
* connection
* 如果是executeQ 有结果集 resultset
* 如果是executeU 有行数返回
* */
public static void close(ResultSet resultSet, Statement statement, Connection connection){
try {
if(resultSet != null){
resultSet.close();
}
if (statement != null){
statement.close();
}
if (connection != null){
connection.close();
}
} catch (SQLException e) {
//把编写异常改为运行异常
throw new RuntimeException(e);
}
}
}