Question

I'm trying to do a batch insert with java in a test database for my college project, but I'm getting an error and I could not figure out why.. selects statements are working but the insert will just not work. thanks in advance.

Error: Exception in thread "main" java.sql.BatchUpdateException: 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 '' at line 1 at com.mysql.jdbc.StatementImpl.executeBatch(StatementImpl.java:1193) at test.main(test.java:29)

    public static void main(String[] args) throws Exception
    {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con = DriverManager.getConnection ("jdbc:mysql://myserverIP:3306/databaseName","root", "");

            Statement statement = con.createStatement();

            String [] queries = {
                "insert into name (first,last) values ('Joao', 'Silva')",
                "insert into name (first,last) values ('Jose', 'Santos')",
                "insert into name (first,last) values ('Lucas', 'Maluco')",
                "insert into name (first,last) values ('Cesar', 'Pereira')",

            };

            for (String query: queries) {
            statement.addBatch(query);
            statement.executeBatch();
            }
            statement.close();
            con.close();
    }
Was it helpful?

Solution

Execute the batch after all the queries has been added to the Statement rather than per individual query

for (String query: queries) {
   statement.addBatch(query);
}
statement.executeBatch();
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top