我必须构建一个sql查询,我必须在字符串中替换两个参数。
- 字符串变量 clean_csv_path 代表路径
- 字符串变量 lines_termination_os 代表Windows或Linux所需的Escape字符 r n,取决于。
在主执行期间,扫描仪类别提供了参数。
这是我的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
您需要的东西称为Java中的准备序列。Google IT,有许多使用此类的示例。另一个问题是,您将其设置为" clean_csv_path"设置LOAD_ALL_ALIASES。它无法在Java中使用。
您需要以相反的方式做事。
首先将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
可以用在运行时返回OS依赖行分隔符返回的System.lineSeparator()
。
以正确的顺序写入它,然后效果很好:
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) ";