mysql 通过 JDBC 执行时出现 LOAD DATA LOCAL INFILE 语法错误

mysql LOAD DATA LOCAL INFILE syntax error when executed via JDBC

我正在尝试使用此示例查询从本地的 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