数据库工具类 DBUtil
// 数据库工具类
public class DBUtil {
// 定义四个常量值
private static final String DRIVER = "com.mysql.jdbc.Driver";
private static final String URL = "jdbc:mysql:///java31?characterEncoding=utf8";
private static final String USER = "root";
private static final String PASSWORD = "root";
// 定义JDBC常用类和接口
private static Connection con = null;
private static Statement st = null;
private static PreparedStatement ps = null;
private static ResultSet set = null;
static {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, USER, PASSWORD);
} catch (Exception e) {
e.printStackTrace();
}
}
// 针对查询的功能
public static ResultSet select(String sql,Object[] args) {
//String sql2 = "select * from account where u_name = ? and password = ?";
try {
// 获取预处理对象
ps = con.prepareStatement(sql);
// 使用sql语句中的占位符 ?
// 遍历数组
// 占位符 在sql中是有前后顺序的 u_name对应的问号 索引是 1 password对应的问号就是2
for (int i = 0; i < args.length; i++) {
// 把问号提换成具体的数据
ps.setObject(i+1, args[i]);
}
// 执行sql语句 获取结果值
set = ps.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
return set;
}
// 针对更新的功能 insert update delete executeUpdate()
public static int update(String sql,Object[] args) {
// 获取预处理对象
// 定义一个变量 用来记录印象数据库表的行数
int count = 0;
try {
ps = con.prepareStatement(sql);
// 使用sql语句中的占位符 ?
// 遍历数组
// 占位符 在sql中是有前后顺序的 u_name对应的问号 索引是 1 password对应的问号就是2
for (int i = 0; i < args.length; i++) {
// 把问号提换成具体的数据
ps.setObject(i+1, args[i]);
}
// 执行sql语句 获取结果值
count = ps.executeUpdate();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// 返回给调用处
return count;
}
// 关闭连接的方法
public static void closeAll() {
// 关闭时 先关闭ResultSet
if (set != null) {
try {
set.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (st != null) {
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}