JdbcUtils.java(数据源连接工具——对原始JDBC操作数据库的简单封装)
JdbcUtils.java(数据源连接工具)
package com.example.jdbctemplateproject.utils.jdbc;
import java.sql.*;
/**
* 数据源连接工具
*
* @author: shipleyleo
* @create: 2023-04-07 17:32:16
*/
public class JdbcUtils {
private static Connection conn;
private static Statement stmt;
private static ResultSet rs;
public static void buildConnection(DataSourceEnum dataSourceEnum) {
buildConnection(dataSourceEnum.getDriverClassName(), dataSourceEnum.getUrl(), dataSourceEnum.getUsername(), dataSourceEnum.getPassword());
}
/**
* 构建数据库连接
*
* @param driverClassName
* @param url
* @param username
* @param password
*/
public static void buildConnection(String driverClassName, String url, String username, String password) {
try {
// 1、注册driver
Class.forName(driverClassName);
// 2、建立数据库连接对象
conn = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* 执行查询
*
* @param sql
* @return
*/
public static ResultSet executeQuery(String sql) {
try {
// 3、建立操作对象
stmt = conn.createStatement();
// 4、结果集
rs = stmt.executeQuery(sql);
} catch (SQLException e) {
e.printStackTrace()