狂神说java超市管理系统dao层(增删改查)

数据库连接(增删改查)

package dao;
import com.mysql.jdbc.Connection;
import java.io.IOException;
import java.io.InputStream;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

public class BaseDao {
    private  static String  driver;
    private  static String  url;
    private  static String  username;
    private  static String  pwd;
    //通过静态加载器读取配置文件
    static {
        InputStream is = BaseDao.class.getClassLoader().getResourceAsStream("db.properties");
        Properties properties = new Properties();
        try {
            properties.load(is);
        } catch (IOException e) {
            e.printStackTrace();
        }
        driver =   properties.getProperty("driver");
        username =   properties.getProperty("username");
        url =   properties.getProperty("url");
        pwd =   properties.getProperty("pwd");
    }
    //通过静态加载器连接数据库
    public  static Connection GetConn() throws ClassNotFoundException, SQLException {
        Class.forName(driver );
       Connection connection = (Connection) DriverManager.getConnection(url,username,pwd);
       return connection;
    }
    //查询数据库方法
    public static ResultSet ExEc(Connection conn,String sql,Object[] params,PreparedStatement pr) throws SQLException{
        pr = conn.clientPrepareStatement(sql);
        ResultSet rs=null;
        for (int i = 0; i <params.length  ; i++) {
            pr.setObject(i+1,params[i]);
            }
        rs = pr.executeQuery();
        return rs;
        }
        //增删改查
    public static int QuDel(Connection conn,String sql,Object[] params,PreparedStatement pr) throws SQLException{
        pr = conn.clientPrepareStatement(sql);
        for (int i = 0; i <params.length  ; i++) {
            pr.setObject(i+1,params[i]);
        }
        int up =  pr.executeUpdate();
        return up;
    }

    //关闭连接
    public  static boolean ConnClose(Connection conn, ResultSet rs,PreparedStatement pr){
        boolean flag = true;
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }
        if (pr != null) {
            try {
                pr.close();
            } catch (SQLException e) {
                e.printStackTrace();
                flag = false;
            }
        }

    return flag;
    }
    }

数据库配置文件

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/smbms?useUnicode=true&characterEncoding=UTF8&useSSL=false&serverTimezone=UTC&rewriteBatchedStatements=true
username=root
pwd=123456

  

上一篇:Invalid bound statement (not found)


下一篇:新闻管理系统(三)封装Service和App