jdbc工具类文件:
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.sql.*;
import java.util.*;
public class JdbcUtils {
//定义全局
private PreparedStatement preparedStatement;
private Connection connection;
private ResultSet resultSet;
//定义properties属性
private static String driver;
private static String url;
private static String user;
private static String password;
//注册驱动,只执行一次
static {
//获取集合
Properties properties=new Properties();
try {
//加载文件
properties.load(new FileReader("文件地址/jdbcsource.properties"));
driver = properties.getProperty("driver");
url = properties.getProperty("url");
user=properties.getProperty("user");
password=properties.getProperty("password");
Class.forName(driver);
} catch (ClassNotFoundException e) {
throw new RuntimeException(e);
} catch (FileNotFoundException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
//获取连接 obj用来判断sql语句中的问号个数同时统一sql语句中的类型
public void getConnection(String sql,Object[] obj){
try {
connection = DriverManager.getConnection(url, user, password);
preparedStatement = connection.prepareStatement(sql);
//给?号赋值
if (obj!=null) {
//遍历obj数组
for (int i = 0; i <obj.length ; i++) {
Object o = obj[i];
preparedStatement.setObject(i+1,o);
}
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
//查询
public List<Map<String,Object>> query(String sql,Object[] obj){
//创建集合存储map集合
List<Map<String,Object>> result=new ArrayList<>();
getConnection(sql,obj);
try {
//执行sql,获取结果集
resultSet = preparedStatement.executeQuery();
while (resultSet.next()) {
//将每一行的数据存入map集合中
Map<String,Object> map=new HashMap<>();
//获取结果集中的列信息
ResultSetMetaData metaData = resultSet.getMetaData();
//获取列数量
int columnCount = metaData.getColumnCount();
for (int i = 1; i <= columnCount; i++) {
//根据每一列获取列名
String columnName = metaData.getColumnName(i);
//根据列名获取结果集中的数据
Object object = resultSet.getObject(columnName);
//数据存入map中
map.put(columnName,object);
}
result.add(map);
}
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
close();
}
return result;
}
//添加修改删除
public int update(String sql,Object[] obj){
//执行方法,获取preparedStatement对象
getConnection(sql,obj);
int i=0;
try {
i = preparedStatement.executeUpdate();
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
close();
}
return i;
}
//关闭
public void close(){
try {
if (resultSet!=null) {
resultSet.close();
}
if (preparedStatement!=null) {
preparedStatement.close();
}
if (connection!=null) {
connection.close();
}
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
}
properties文件:
driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/xxxx
user=root
password=root