一个简单的JDBC工具类(目前还没有学到PreparedStatement) jdbc .properties
需配置在src目录下。
import java.io.FileReader;
import java.io.IOException;
import java.net.URL;
import java.sql.*;
import java.util.Properties;
/**
3. @author 菠菜饭团
4. @title: JDBCUtils
5. @date 2020/11/24 15:05
*/
public class JDBCUtils {
private static String url;
private static String user;
private static String password;
private static String driver;
/**
* 使用properties配置文件来获取数据库 连接
*/
static{
Properties pro = new Properties();
ClassLoader classLoader = JDBCUtils.class.getClassLoader();
URL res = classLoader.getResource("jdbc .properties");
String path = res.getPath();
try {
// pro.load(new FileReader("jdbc .properties"));
pro.load(new FileReader(path));
url = pro.getProperty("url");
user = pro.getProperty("username");
password = pro.getProperty("password");
driver = pro.getProperty("driverClassName");
//注册驱动
Class.forName(driver);
} catch (IOException | ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() throws SQLException {
return DriverManager.getConnection(url,user,password);
}
/**
* @description: 释放资源
* @author 菠菜饭团
* @date 2020/11/24 15:10
*/
public static void close(ResultSet resultSet, Statement statement,Connection connection) throws SQLException {
if(resultSet!=null){
resultSet.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}
}