2

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?

2 Answers 2

3

For future reference, I also had to add:

&allowLoadLocalInfile=true

to the connection string to avoid error:

ERROR 3950 (42000): Loading local data is disabled; this must be enabled on both the client and server side
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.