前端页面输入SQL语句,后端用jdbc连接查询

1、Utils类

public class PageUtils {

    /**
     * 分页函数
     * @param currentPage   当前页数
     * @param pageSize  每一页的数据条数
     * @param list  要进行分页的数据列表
     * @return  当前页要展示的数据
     */
    public static Page getPages(int currentPage, int pageSize, List list){
        Page page = new Page();
        int size = list.size();

        if(pageSize > size) {
            pageSize = size;
        }

        // 求出最大页数,防止currentPage越界
        int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;

        if(currentPage > maxPage) {
            currentPage = maxPage;
        }

        // 当前页第一条数据的下标
        int curIdx = currentPage > 1 ? (currentPage - 1) * pageSize : 0;

        List pageList = new ArrayList();

        // 将当前页的数据放进pageList
        for(int i = 0; i < pageSize && curIdx + i < size; i++) {
            pageList.add(list.get(curIdx + i));
        }

        page.setCurrent(currentPage).setSize(pageSize).setTotal(list.size()).setRecords(pageList);
        return page;
    }

    /**
     * 分页函数
     * @param currentPage   当前页数
     * @param pageSize  每一页的数据条数
     * @param total 数据总数
     * @param list  查询到的数据
     * @return  当前页要展示的数据
     */
    public static Page getPages(int currentPage, int pageSize,int total, List list){
        Page page = new Page();
        int size = total;

        if(pageSize > size) {
            pageSize = size;
        }

        // 求出最大页数,防止currentPage越界
        int maxPage = size % pageSize == 0 ? size / pageSize : size / pageSize + 1;

        if(currentPage > maxPage) {
            currentPage = maxPage;
        }



        page.setCurrent(currentPage).setSize(pageSize).setTotal(total).setRecords(list);
        return page;
    }

}

2、业务层

/**
 * ${comments}
 * sql查询
 *
 * @author luoqianqian
 * @email *****@mail.com
 * @date 2021.3.9 9:27
 */
@Service
public class KsCorpSqlInfoExportServiceImpl implements KsCorpSqlInfoExprotService {

    @Autowired
    private KsCorpInfoExprotMapper infoExprotMapper;

    @Autowired
    private KsCorpSqlInfoExprotMapper sqlInfoExprotMapper;

    @Autowired
    private SysDictDetailMapper dictDetailMapper;

    @Override
    public Object findListByPage(KsCorpSqlInfoExportEntity sqlInfoExportEntity) {
        /*QueryWrapper<KsCorpInfoExprotEntity> wrapper2 = new QueryWrapper<>();
        wrapper2.apply(sqlInfoExportEntity.getSql());
        List<KsCorpInfoExprotEntity> aa = infoExprotMapper.selectList(wrapper2);*/

        //返回给前端的错误提示
        String toFront = "查询有误,请重新输入查询";

        //判断当前页和每页显示是否为null
        if(sqlInfoExportEntity.getPage() == null){
            sqlInfoExportEntity.setPage(1);
        }
        if(sqlInfoExportEntity.getLimit() == null){
            sqlInfoExportEntity.setLimit(10);
        }

        //防止 sql注入风险:
        //是否为查询语句
        boolean isSelect = sqlInfoExportEntity.getSql().indexOf("s") == 0;
        // “;” 是否存在,如果存在,是否在语句的末尾
        boolean isExistSemicolon = (sqlInfoExportEntity.getSql().lastIndexOf(";") == (sqlInfoExportEntity.getSql().length() - 1))
                || (!sqlInfoExportEntity.getSql().contains(";"));

        if (isSelect && isExistSemicolon){
            /*//查询 sys_dict_detail 表的 机构状态
            QueryWrapper<SysDictDetailEntity> wrapper = new QueryWrapper<>();
            List<String> valueList = new ArrayList<>();*/

            //以一个空格或多个空格分割SQL语句字符串
            String[] sqlKeywordArray = sqlInfoExportEntity.getSql().split("\\s+");
            String tableName = sqlKeywordArray[3];
            //获取需要实例化的对象的类名
            String entityName = tableName;
            for(int i =0 ; i< tableName.length() ; i++) {
                String temp = tableName.charAt(i) + "";
                if (temp.equals("_")) {
                    entityName = entityName.substring(0,1).toUpperCase() + entityName.substring(1,i+1) + entityName.substring(i+1,i+2).toUpperCase() + entityName.substring(i+2);
                }
            }
            entityName = entityName.replace("_","");
            System.out.println(entityName);

            //根据表名查询该表的所有字段的名称
            List<String> columns = sqlInfoExprotMapper.selectAllTableColumn(tableName);

            Connection conn = null;
            PreparedStatement ps = null;
            ResultSet rs = null;

            int count = 0;

            //判断是否有数据查询到
            Boolean isSelectData = false;
            //查询数据的总量 和失去了语句
            Integer total = null;
            String totalSql = "";

            //把实体类的添加到 List
            List entityList = new ArrayList<>();
            try{
                //注册驱动
                Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
                //设置链接地址
                /*String url ="jdbc:sqlserver://223.112.127.3:8001;databaseName=farenkuj";
                String user = "sa";
                String password = "yg@2019";*/

                String url ="jdbc:sqlserver://10.36.1.201:1433;databaseName=farenku";
                String user = "frk";
                String password = "yg@frk@2020";
                //连接数据库
                conn = DriverManager.getConnection(url,user,password);
                //获取语句执行平台,并创建数据库查询
                String sql = "";
                //判断是否有 where
                boolean isHaveWhere = false;
                for(int i = 0;i<sqlKeywordArray.length;i++){
                    sql += sqlKeywordArray[i] + " ";
                    if (sqlKeywordArray[i].toLowerCase().equals("select")){
                        sql+=" top " + sqlInfoExportEntity.getLimit() + " ";
                    }
                    if (sqlKeywordArray[i].toLowerCase().equals("where")){
                        sql+=" " + sqlKeywordArray[3] + ".data_id not in (select top " + sqlInfoExportEntity.getLimit()*(sqlInfoExportEntity.getPage()-1)
                                + " data_id " + " from " + sqlKeywordArray[3] + ") and ";
                        isHaveWhere = true;
                    }
                    //判断如果是最后一次循环并且没有 where 的话,拼接 where 上去
                    if (i == sqlKeywordArray.length -1){
                        if (!isHaveWhere){
                            sql += " where " + sqlKeywordArray[3] + ".data_id not in (select top " + sqlInfoExportEntity.getLimit()*(sqlInfoExportEntity.getPage()-1)
                                    + " data_id " + " from " + sqlKeywordArray[3] + ")";
                        }
                    }
                }
                //
                totalSql = "select count(*) total from (" + sqlInfoExportEntity.getSql() + ") a;";

                ps = conn.prepareStatement(sql);



                //执行查询语句
                rs = ps.executeQuery();
                while (rs.next()){

                    //total = rs.getInt("total");

                    if (count==0){
                        //进入这里则代表查询到了数据
                        isSelectData = true;
                        count++;
                    }


                    //动态创建实例
                    Object entity = Class.forName("com.company.project.entity." + entityName + "Entity").newInstance();
                    Class infoExportEntityClass = entity.getClass();
                    Field[] fields = infoExportEntityClass.getDeclaredFields();
                    //利用循环
                    for (int i = 0;i < fields.length;i++){
                        //设置私有属性的访问权限
                        fields[i].setAccessible(true);
                        //获取字段的名称
                        String filedName = fields[i].getName();
                        //在大写字母前添加 “_” 符号
                        String name = filedName.replaceAll("[A-Z]", "_$0");
                        name = name.toLowerCase();

                        //获取字段类型
                        String type = fields[i].getGenericType().toString();

                        //判断实体类属性与表的字段名是否一致
                        for (int j = 0;j < columns.size();j++){
                            if(name.equals(columns.get(j))){
                                //再判断字段的类型
                                switch (type){
                                    case "class java.lang.String":
                                        fields[i].set(entity,rs.getString(name));
                                        break;
                                    case "class java.lang.Integer":
                                        fields[i].set(entity,rs.getInt(name));
                                        break;
                                    case "class java.util.Date":
                                        fields[i].set(entity,rs.getTimestamp(name));
                                        break;
                                }

                            }
                        }


                    }


                    //添加到实体类集合
                    entityList.add(entity);

                }

            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            } catch (SQLException e) {
                e.printStackTrace();
                toFront = "不好意思,您输入的SQL语句在" + e.getMessage() +"请重新输入!";
                return toFront;
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            } catch (InstantiationException e) {
                e.printStackTrace();
            } finally {
                if (null != conn){
                    try{
                        conn.close();
                        conn = null;
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (null != ps){
                    try{
                        ps.close();
                        ps = null;
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
                if (null != rs){
                    try{
                        rs.close();
                        rs = null;
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }

            total = sqlInfoExprotMapper.selectCount(totalSql);

            //如果没查询到数据,则返回给前端 无数据
            if (!isSelectData){
                toFront = "无数据";
                return toFront;
            }

            //数据分页设置
            Page page = PageUtils.getPages(sqlInfoExportEntity.getPage(),sqlInfoExportEntity.getLimit(),total,entityList);

            //批量查询 sys_dict_detail 1349172937746477058
            QueryWrapper<SysDictDetailEntity> wrapper = new QueryWrapper<>();
            wrapper.eq("dict_id","1349172937746477058");
            List<SysDictDetailEntity> dictDetailEntities = dictDetailMapper.selectList(wrapper);

            //设置机构状态
            for (Object o : page.getRecords()) {

                Class entityClass = o.getClass();
                Field[] fields = entityClass.getDeclaredFields();
                for(int i = 0;i < fields.length;i++){
                    //设置私有属性的访问权限
                    fields[i].setAccessible(true);

                    //获取字段的名称
                    String filedName = fields[i].getName();

                    if(filedName.equals("corpStatusName")){
                        //遍历 sys_dict_detail 表的数据
                        for (SysDictDetailEntity dictDetailEntity : dictDetailEntities) {
                            try {

                                if (fields[i-1].get(o) != null){
                                    if (fields[i-1].get(o).equals(dictDetailEntity.getValue())) {
                                        fields[i].set(o, dictDetailEntity.getLabel());
                                    }
                                }

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


                }
            }

            return page;


        }




        return toFront;
    }
}

好的,以下是一个简单的Java前端连接SQL Server后端的示例代码,你可以根据自己的需求进行调整。 前端代码: ```java import java.sql.*; import java.util.ArrayList; import java.util.List; public class Frontend { public static void main(String[] args) { Connection conn = null; try { // 加载驱动程序 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 连接数据库 String url = "jdbc:sqlserver://localhost:1433;databaseName=test"; String user = "sa"; String password = "123456"; conn = DriverManager.getConnection(url, user, password); // 查询数据 String sql = "SELECT * FROM user"; Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery(sql); // 处理结果集 List<User> userList = new ArrayList<>(); while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); User user = new User(id, name, age); userList.add(user); } // 输出数据 for (User user : userList) { System.out.println(user); } // 关闭连接 resultSet.close(); statement.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } ``` 后端代码: ```java import java.sql.*; import java.util.ArrayList; import java.util.List; public class Backend { public List<User> getUsers() { Connection conn = null; List<User> userList = new ArrayList<>(); try { // 加载驱动程序 Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); // 连接数据库 String url = "jdbc:sqlserver://localhost:1433;databaseName=test"; String user = "sa"; String password = "123456"; conn = DriverManager.getConnection(url, user, password); // 查询数据 String sql = "SELECT * FROM user"; Statement statement = conn.createStatement(); ResultSet resultSet = statement.executeQuery(sql); // 处理结果集 while (resultSet.next()) { int id = resultSet.getInt("id"); String name = resultSet.getString("name"); int age = resultSet.getInt("age"); User user = new User(id, name, age); userList.add(user); } // 关闭连接 resultSet.close(); statement.close(); conn.close(); } catch (ClassNotFoundException e) { e.printStackTrace(); } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } } return userList; } } ``` 这段代码使用了SQL Server数据库,你需要先下载并安装SQL Server,并且在代码中修改相应的数据库连接信息。同时,你需要在前端代码中执行SQL语句查询数据库,将查询结果封装成List<User>对象,并在后端代码中调用前端代码来获取数据。这里我定义了一个User类来封装查询结果,你可以根据自己的需求进行调整。
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值