JDBC封装为工具类
1.在src/main/resource下创建mysql.properties配置文件
2.加载配置文件
3.加载驱动 Class.forName(driver);
4.创建连接对象
Connection conn = DriverManager.getConnection(url, user, password)
5.创建Statement语句
6.创建SQL语句
7.返回结果集
8.释放资源
mysql.properties:
driver = com.mysql.cj.jdbc.Driver url = jdbc:mysql://localhost:3306/test?characterEncoding=utf8 user = root password = 123456
JdbcUtils
package com.suyan.Utils;
import java.sql.*;
import java.util.Properties;
public class JdbcUtils {
private static String driver = null ;
private static String url = null ;
private static String user = null ;
private static String password = null ;
//提供静态代码块:随着类的加载而加载
static {
//通过Properties对象获取配置文件的信息
Properties properties = new Properties();
//当配置文件放在src/main/resources的目录下时,只能使用Class.getResourceAsStream()方法来加载
try {
properties.load(JdbcUtils.class.getClassLoader().getResourceAsStream("mysql.properties"));
driver = properties.getProperty("driver");
user = properties.getProperty("user");
password = properties.getProperty("password");
url = properties.getProperty("url");
//注册驱动
Class.forName(driver);//建议写上
} catch (Exception e) {
throw new RuntimeException(e);
}
}
//获取连接对象
public static Connection getConnection() {
try {
Connection connection = DriverManager.getConnection(url, user, password);
System.out.println("数据库连接成功~");
return connection;
} catch (SQLException e) {
System.out.println("数据库连接失败~");
throw new RuntimeException(e);
}
}
//设置自动提交
public static void setAutoCommit(Connection conn, boolean flag){
try{
if(flag == false){
conn.setAutoCommit(false);
}
}catch(Exception e){
throw new RuntimeException(e);
}
}
//预处理SQL语句
public static PreparedStatement prepareStatement(Connection conn, String sql){
try{
PreparedStatement ps = conn.prepareStatement(sql);
return ps;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//查询处理集的next()方法
public static boolean next(ResultSet rs){
try{
boolean flag = rs.next();
return flag;
}catch(Exception e){
throw new RuntimeException(e);
}
}
//释放资源
public static void close(Connection conn, Statement...statement){
//关于多条SQL语句,使用可变长形参列表来对其进行关闭
for(int i=0;i


