Пакетное обновление jdbc не выполняется для нескольких операторов - PullRequest
0 голосов
/ 23 декабря 2018

Я запускаю обновления базы данных mysql в потоке в Java, и у меня возникает странная проблема: если у меня в пакете 4 или менее операторов, это проходит без проблем, но если у меня 5 илибольше я получаю исключение синтаксиса sql, и только первое утверждение проходит через.Я пробовал это с тем же утверждением, поэтому я уверен, что синтаксис правильный.Может ли кто-нибудь помочь мне понять, что происходит?

для драйвера jdbc, который я использую com.mysql.cj.jdbc.Driver из mysql-connector-java-8.0.12.jar, который поставляется в комплекте с mysql.Вот код для рассматриваемого класса:

public class DBwriteThread extends Thread {

private final Statement state;
//execute batch after number of statements
public static final int BATCH_EXEC_SIZE = 5;

//# of strings added to the current batch
private int queryC;
private String tmpQueryStr;

private final BlockingQueue<String> queryStrQueue;

public DBwriteThread(Connection con, BlockingQueue<String> q) throws SQLException{
    this.queryC = 0;

    setName("DBwriteThread");

    state = con.createStatement();
    queryStrQueue = q;
}

@Override
public void run() {
    System.out.println(Thread.currentThread().getName() + " runs");
    while(true){
        try {
                tmpQueryStr = queryStrQueue.take(); //take blocks the thread

                System.out.println(tmpQueryStr);
                if (tmpQueryStr != "fc"){
                    state.addBatch(tmpQueryStr);
                    queryC++;
                }

                if(queryC >= BATCH_EXEC_SIZE || tmpQueryStr == "fc"){ 
                    System.out.println(state.toString());
                    state.executeBatch();
                    reportCommit();
                    queryC = 0;
                }
        } 
        catch (SQLException ex) {
            System.err.println(ex.getSQLState());
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        } 
    }
} 
[...]
}

вот вывод, который я получаю из операторов печати, и исключение:

//output 4 statements:
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
fc
com.mysql.cj.jdbc.StatementImpl@5123cf89
DBwriteThread: commiting 4 statements to database


//output 5 statements:
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdasd99as");
com.mysql.cj.jdbc.StatementImpl@5123cf89
42000
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 ';INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdas' at line 1
    at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
    at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
    at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
    at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
    at com.mysql.cj.util.Util.handleNewInstance(Util.java:210)
    at com.mysql.cj.util.Util.getInstance(Util.java:185)
    at com.mysql.cj.util.Util.getInstance(Util.java:192)
    at com.mysql.cj.jdbc.exceptions.SQLError.createBatchUpdateException(SQLError.java:224)
    at com.mysql.cj.jdbc.StatementImpl.executeBatchUsingMultiQueries(StatementImpl.java:1052)
    at com.mysql.cj.jdbc.StatementImpl.executeBatchInternal(StatementImpl.java:860)
    at com.mysql.cj.jdbc.StatementImpl.executeBatch(StatementImpl.java:813)
    at shop.db.DBwriteThread.run(DBwriteThread.java:59)
Caused by: java.sql.SQLSyntaxErrorException: 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 ';INSERT INTO products VALUES ( NULL,"prod 9","90.33","5","1","some text99dfasdas' at line 1
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
    at com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:97)
    at com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
    at com.mysql.cj.jdbc.StatementImpl.executeInternal(StatementImpl.java:781)
    at com.mysql.cj.jdbc.StatementImpl.execute(StatementImpl.java:798)
    at com.mysql.cj.jdbc.StatementImpl.executeBatchUsingMultiQueries(StatementImpl.java:1038)
    ... 3 more

таблица из приведенных выше примеров настроенавот так:

CREATE TABLE products
(
    productId       INT unsigned NOT NULL AUTO_INCREMENT,
    productName     VARCHAR(150) NOT NULL,
    price           DECIMAL(13,2) NOT NULL, 
    categoryId      INT unsigned NOT NULL,
    active          TINYINT(1) unsigned NOT NULL, 
    description     TEXT NULL,
    PRIMARY KEY     (productId),
    FOREIGN KEY     (categoryId) REFERENCES productCategories(productCategoriyId)    
);
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...