我正在尝试使用此示例查询从本地的csv文件加载内容:
SET GLOBAL local_infile=1; LOAD DATA LOCAL INFILE 'C:/afc_orders.csv' INTO TABLE `afc_report`.`afc_orders` FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '"' LINES TERMINATED BY '\n' IGNORE 1 ROWS (`type_o`,`n_order`,`n_return`);
从MySQL执行查询非常有效,但是,当我尝试从JDBC执行相同的查询时,出现语法错误:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'LOAD DATA LOCAL INFILE 'C:/afc_orders.csv' INTO TABLE `afc_report`.`afc_orders` ' at line 1
这是我的代码:
Connection conn = null;
String url = "jdbc:mysql://" + mysqlHost + ":" + mysqlPort + "/" + mysqlDatabase + "?useUnicode=true&useJDBCCompliantTimezoneShift=true&useLegacyDatetimeCode=false&serverTimezone=UTC";
try {
conn = DriverManager.getConnection(url, mysqlUser, mysqlPassword);
Statement stmt = conn.createStatement();
String sql = "SET GLOBAL local_infile=1; LOAD DATA LOCAL INFILE 'C:/afc_orders.csv' INTO TABLE `afc_report`.`afc_orders` FIELDS TERMINATED BY ';' OPTIONALLY ENCLOSED BY '\"' LINES TERMINATED BY '\\n' (`type_o`,`n_order`,`n_return`);";
System.out.println(sql);
stmt.execute(sql);
} catch(Exception e) {
System.out.println(e.getMessage());
}
这是我正在使用的驱动程序:
<!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>8.0.20</version>
</dependency>
我想念什么?
您的代码试图同时执行两个语句(SET
语句和LOAD DATA
语句,但是Statement.execute(...)
仅接受单个语句,而不是多个语句。
[您可以尝试分别执行这些语句(我通常不使用MySQL,因此不确定在这种情况下是否可行),或者可以将MySQL Connector / J驱动程序配置为允许添加多条语句,连接字符串中的连接属性allowMultiQueries=true
。
供将来参考,我还必须添加:
&allowLoadLocalInfile=true
到连接字符串以避免错误:
ERROR 3950 (42000): Loading local data is disabled; this must be enabled on both the client and server side