jdbc工具类

public class DBUtils {

//    static String user = "root";
//    static String password = "root";
    static String user = "root";
    static String password = "root";
    static String url = "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&serverTimezone=Asia/Shanghai";
    static String driver = "com.mysql.cj.jdbc.Driver";
    static Connection conn = null;
    static ResultSet rs = null;
    static PreparedStatement ps = null;

    /**
     * 初始化数据库
     *
     * @return
     */
    public static Connection getConnection() {
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, user, password);
        } catch (Exception e) {
            System.out.println("数据库连接异常");
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 修改操作
     *
     * @param sql
     * @return
     */
    public static int addUpdDel(String sql) {
        int i = 0;
        try {
            PreparedStatement ps = conn.prepareStatement(sql);
            i = ps.executeUpdate();
        } catch (SQLException e) {
            System.out.println("sql数据库增删改异常");
            e.printStackTrace();
        }
        return i;
    }

    /**
     * 查询操作
     *
     * @param sql
     * @return
     */
    public static ResultSet selectSql(String sql) {
        try {
            ps = conn.prepareStatement(sql);
            rs = ps.executeQuery(sql);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            System.out.println("sql数据库查询异常");
            e.printStackTrace();
        }

        return rs;
    }


    /**
     * 关闭连接
     *
     * @param conn
     */
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                System.out.println("数据库关闭异常");
                e.printStackTrace();
            }
        }
    }
}

  

posted @ 2021-11-02 09:47  二先森  阅读(32)  评论(0编辑  收藏  举报