smbms超市管理项目-项目建立,数据库工具类编写

1、首先用maven工具创建项目

2、配置相关的properties驱动文件

driver=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&useCharacterEncoding=utf8&useSSL=false
username=root

password=123456

3、Dao层编写基础的工具类

package com.liu.dao;

import java.io.IOException;
import java.io.InputStream;
import java.sql.*;
import java.util.Properties;

public class BasicDao {

private static String driver;
private static String url;
private static String username;
private static String password;

static{

InputStream res = BasicDao.class.getClassLoader().getResourceAsStream("db.properties");

Properties pr = new Properties();

try {
pr.load(res);

} catch (IOException e) {
e.printStackTrace();
}

driver = pr.getProperty("driver");
url = pr.getProperty("url");
username = pr.getProperty("username");
password = pr.getProperty("password");
}

public static Connection getConnection(){
Connection connection = null;
try {
Class.forName(driver);
connection = DriverManager.getConnection(url,username,password);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}

//查询数据
public static ResultSet execute(Connection co,ResultSet res,PreparedStatement prep,String sql,
Object[] para){

try {
prep = co.prepareStatement(sql);
for (int i = 0; i < para.length; i++) {
prep.setObject(i+1,para[i]);
}

res = prep.executeQuery();

} catch (SQLException e) {
e.printStackTrace();
}
return res;
}

//增删改、函数重载机制
public static int execute(Connection co,PreparedStatement prep,String sql,Object[] objects){
int i = 0;
try {
prep = co.prepareStatement(sql);
for (int j = 0; j < objects.length; j++) {
prep.setObject(j+1,objects[j]);
}
i = prep.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
return i;
}

//释放资源
public static boolean closeResource(Connection connection,PreparedStatement preparedStatement,ResultSet resultSet){
boolean flag = true;
if (connection != null) {
try {
connection.close();
// GC回收
connection = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
}
if (preparedStatement != null) {
try {
preparedStatement.close();
preparedStatement = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}
}
if (resultSet != null) {
try {
resultSet.close();
// 垃圾回收机制回收
resultSet = null;
} catch (SQLException e) {
flag = false;
e.printStackTrace();
}

}

return flag;
}
}

 


 
posted @ 2022-06-05 23:42  努力学习の小白  阅读(56)  评论(0编辑  收藏  举报
Live2D