如何使用SQL查询中的方法返回的字符串值

时间:2019-02-27 12:20:04

标签: java

我有一种getSites()方法,该方法从csv文件返回所有site_names。现在,我想在SQL查询中使用该返回的字符串变量。这是getSites()方法:

public class ReadCSVFile {

    public static String getSites() {
        // .csv comma separated values
        String csvFile = "C:\\data.csv";
        BufferedReader br = null;
        String line = "";
        String sites = "";

        try {
            br = new BufferedReader(new FileReader(csvFile));
            while ((line = br.readLine()) != null) {
                sites = sites + line + ",";
            }
            sites = sites.substring(0, sites.length() - 1);
            // System.out.println(sites);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (br != null) {
                try {
                    br.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return sites;
    }
}

这是我要在此SQL查询中使用的值:

String query = select NodeID, Site_Name from csproperties where Site_Name IN ("+sites+") ORDER BY Site_Name

因此,当我在("+sites+")中传递string的值时,查询变量将触发,并根据site_names获得API输出。

现在,我在com.gds.service包下创建了GFNSService的类文件,在其中创建了API的getRigStatistics方法,并且在此方法下,我希望代码获取以下项的(“ + sites +”)下的站点值sql查询如下-

@GET

@Produces({MediaType.APPLICATION_JSON,MediaType.APPLICATION_XML}) @Path(“ / getRigStatistics”) 公共列表getRigStatistics(@HeaderParam(“ authorization”)字符串authString){             logger.info(“ API方法getRigStatistics被调用。”);

        if (!isAppDynamicsUserAuthenticatedRigStatistics(authString)) {
            throw new WebApplicationException(Response.status(Response.Status.UNAUTHORIZED).build();
        }

List rigList = new ArrayList <>();

        String query = "String query = select NodeID, Site_Name from csproperties where Site_Name IN ("+sites+") ORDER BY Site_Name";.....and so on  code to map properties.....

因此,基本上,我想要一个代码,在该代码中应在getRigStatistics方法中创建一个方法,以将该站点值获取到(“ + sites +”)中。

1 个答案:

答案 0 :(得分:0)

我想您的getSites()返回的字符串如下所示:

String sites = "site1,site2,site3,site4"; 

您不能在SQL查询中使用它,因为它的语法应类似于:

SELECT .... IN ('site1','site2','site3','site4') ...;

要从您的方法中获得这样的字符串,一种可能的方法可能是更改:

 return sites;  

return Stream.of(sites.split(",")).collect(Collectors.joining("','", "'", "'"));

或者,如果您不想使用流,请更改

String sites = "";           to    String sites = "'";
sites = sites + line + ",";  to    sites = sites + line + "','";
sites = sites.substring(0, sites.length() - 1); to  sites = sites.substring(0, sites.length() - 2);
and keep return sites;