package com.uitl;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class DBHelper {
static Connection conn;
static PreparedStatement ps;
static ResultSet rs;
static String driver = "com.mysql.jdbc.Driver";
static String url = "jdbc:mysql://localhost:3306/newsmanagersystem?characterEncoding=UTF-8";// 连接字符串
static String uname = "root";
static String pwd = "";
// 获取数据库连接
public static Connection ConnDB() {
try {
Class.forName(driver);
conn = DriverManager.getConnection(url, uname, pwd);
}catch (ClassNotFoundException e) {
e.printStackTrace();
}catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
// 查询(可变参数)
public static ResultSet ExcuteQuery(String sql, Object... params) {
conn = ConnDB();
try {
PreparedStatement ps = conn.prepareStatement(sql);
// 设置问号值
for (int j = 0; j < params.length; j++) {
Object object = params[j];
ps.setObject(j + 1, object);
}
//执行
rs = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
//增删改(可变参数)
public static Boolean ExcuteNoQuery(String sql, Object... params) {
conn = ConnDB();
int i = 0;
try {
PreparedStatement ps = conn.prepareStatement(sql);
// 设置问号值
for (int j = 0; j < params.length; j++) {
Object object = params[j];
ps.setObject(j + 1, object);
}
i = ps.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i > 0;
}
//释放资源
public static void ClossResource() {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
ps = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
数据库操作类DBHelper(Java版)
最新推荐文章于 2021-07-01 12:24:01 发布