用mysql-connector-java操作数据库(JDBC)

1、添加maven依赖

        
        
            mysql
            mysql-connector-java
            8.0.29
        

2、单处理:更新、删除、插入

    public int singleOperate(String sql, Map map) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
        PreparedStatement ps = conn.prepareStatement(sql);
        for (Map.Entry entry : map.entrySet()) {
            ps.setString(entry.getKey(), entry.getValue());
        }
        int i = ps.executeUpdate();
        ps.close();
        conn.close();
        return i;
    }

3、批处理:更新、删除、插入

    public String batchOperate(String sql, List> list) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
        PreparedStatement ps = conn.prepareStatement(sql);
        for (Map map : list) {
            for (Map.Entry entry : map.entrySet()) {
                ps.setString(entry.getKey(), entry.getValue());
            }
            ps.addBatch();//添加到同一个批处理中
        }
        String str_re = Arrays.toString(ps.executeBatch());
        ps.close();
        conn.close();
        return str_re;
    }

4、查询

    public ResultSet query(String sql) throws ClassNotFoundException, SQLException {
        Class.forName("com.mysql.cj.jdbc.Driver");
        Connection conn = DriverManager.getConnection(sql_host, sql_user, sql_password);
        Statement stmt = conn.createStatement();
        return stmt.executeQuery(sql);
    }

你可能感兴趣的:(SQL,java,数据库,mysql)