Search code examples
javamysqljdbcload-data-infile

mysql LOAD DATA LOCAL INFILE syntax error when executed via JDBC


I am trying to load contents from a csv file a local using this sample query:

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`);

Executing the query from MySQL works perfectly but, when I try to execute the same query from JDBC, I get a syntax Error:

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

Here is my code:

    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());
    }

And here is the driver I am using:

    <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>8.0.20</version>
    </dependency>

What am I missing?


Solution

  • Your code is attempting to execute two statements at once (the SET statement and the LOAD DATA statement), but a Statement.execute(...) only accepts a single statement, not multiple statements.

    You could try to execute these statements separately (I don't normally use MySQL, so I'm not sure if that works in this case), or the MySQL Connector/J driver can be configured to allow multiple statements by adding the connection property allowMultiQueries=true in the connection string.