package com.czb.util;
import java.sql.*;
import java.util.*;
public class DButil {
private static DButil myDButil = new DButil();
private DButil(){
}
public static DButil getMyDButil(){
return myDButil;
}
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://localhost:3306/mydb?useSSL=false&serverTimezone=UTC&characterEncoding=utf8";
private static String username = "root";
private static String password = "root";
private static Connection conn;
private static PreparedStatement ps;
private static ResultSet rs;
static {
try {
Class.forName(driver);
System.out.println("加载驱动成功");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public List<Map> select(String sql,Object...objs){
List<Object> objects = Arrays.asList(objs);
List<Map> list = new ArrayList<>();
try {
conn = DriverManager.getConnection(url,username,password);
ps = conn.prepareStatement(sql);
for (int i = 0; i < (sql+" ").split("\\?").length-1; i++) {
ps.setObject(i+1,objects.get(i));
}
rs = ps.executeQuery();
//ResultSetMetaData 类
//可用于获取关于 ResultSet 对象中列的类型和属性信息的对象:
ResultSetMetaData metaData = rs.getMetaData();
while (rs.next()){
Map map = new HashMap();
for (int i = 1; i <= metaData.getColumnCount(); i++) {
String key = metaData.getColumnName(i);
map.put(key,rs.getObject(key));
}
list.add(map);
}
} catch (SQLException e) {
e.printStackTrace();
}finally {
close();
}
return list;
}
public int update(String sql,Object...objs){
List<Object> objects = Arrays.asList(objs);
int is = 0;
try {
conn = DriverManager.getConnection(url,username,password);
ps = conn.prepareStatement(sql);
for (int i = 0; i < (sql+" ").split("\\?").length-1; i++) {
ps.setObject(i+1,objects.get(i));
}
is = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}finally {
close();
}
return is;
}
public static void close(){
try {
if(conn != null)conn.close();
if(ps != null)ps.close();
if(rs != null)rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
jdbc方法封装直接调用
最新推荐文章于 2023-03-14 22:12:15 发布