2

我必须构建一个 SQL 查询,我必须在其中替换字符串中的两个参数。

  • 代表路径的字符串变量CLEAN_CSV_PATH
  • 字符串变量LINES_TERMINATED_OS 表示 Windows 或 linux 所需的转义字符 \r\n,取决于。

这些参数是在使用 Scanner 类执行 Main 期间提供的。

这是我的 SQL 字符串:

private static String LOAD_ALL_ALIASES = //

        "LOAD DATA LOCAL INFILE '" + CLEAN_CSV_PATH + "' INTO TABLE plantbiocore.Alias " //
                + "FIELDS TERMINATED BY ',' " //
                + "OPTIONALLY ENCLOSED BY  '\"' "
                + "LINES TERMINATED BY '" + LINES_TERMINATED_OS + "'"
                + "IGNORE 1 LINES " //
                + "(locus_id, organism_id, variable, alias) "; //



 Scanner scanner = new Scanner(System.in);
 CLEAN_CSV_PATH = scanner.next() // Here the CLEAN_CSV_PATH does not appear in my LOAD_ALL_ALIASES 
4

3 回答 3

1

你需要以相反的方式做事情。
首先CLEAN_CSV_PATH用扫描仪设置。然后解决你的字符串。
为了允许创建不同的查询CLEAN_CSV_PATH,您可以将其提取到接受参数的方法中。

public void foo(){
   Scanner scanner = new Scanner(System.in);
   String csvPath = scanner.next()
   String query = getQuery(csvPath);         
   // ...
}

private static String getQuery(String csvPath){

       return "LOAD DATA LOCAL INFILE '" + csvPath + "' INTO TABLE plantbiocore.Alias " //
                + "FIELDS TERMINATED BY ',' " //
                + "OPTIONALLY ENCLOSED BY  '\"' "
                + "LINES TERMINATED BY '" + LINES_TERMINATED_OS + "'"
                + "IGNORE 1 LINES " //
                + "(locus_id, organism_id, variable, alias) "; //
}

请注意,LINES_TERMINATED_OS可以替换为System.lineSeparator()在运行时返回依赖于操作系统的行分隔符。

于 2018-02-22T13:01:52.153 回答
1

What you need is called PreparedStatement in java. Google it, there are many examples of using this class. The other problem is that you are setting CLEAN_CSV_PATH after you used it to set LOAD_ALL_ALIASES. It can't work in Java.

于 2018-02-22T12:56:48.743 回答
0

以正确的顺序编写它,然后它将正常工作:

    String LOAD_ALL_ALIASES;
    String CLEAN_CSV_PATH;
    String LINES_TERMINATED_OS;

    Scanner scanner = new Scanner(System.in);
    CLEAN_CSV_PATH = scanner.next();
    LINES_TERMINATED_OS = scanner.next();

    LOAD_ALL_ALIASES = "LOAD DATA LOCAL INFILE '" + CLEAN_CSV_PATH + "' INTO TABLE plantbiocore.Alias " //
            + "FIELDS TERMINATED BY ',' " //
            + "OPTIONALLY ENCLOSED BY  '\"' "
            + "LINES TERMINATED BY '" + LINES_TERMINATED_OS + "'"
            + "IGNORE 1 LINES " //
            + "(locus_id, organism_id, variable, alias) ";
于 2018-02-22T13:01:07.893 回答