Multiple insert statements in single ODBC ExecuteNonQuery (C#)

社会主义新天地 提交于 2019-11-26 23:29:45

问题


I'm inserting multiple rows into a DB, and joining them together in an attempt to improve performance. I get an ODBCException telling me my SQL syntax is wrong. But when I try it in the mysql commandline client, it works just fine.. I ran a simplified test to describe the process.

Command Line Client:


mysql> create table test (`id` int, `name` text);
Query OK, 0 rows affected (0.05 sec)

mysql> INSERT INTO test(id, name) VALUES ('1', 'Foo');INSERT INTO test(id, name) VALUES ('2', 'bar');
Query OK, 1 row affected (0.00 sec)

Query OK, 1 row affected (0.00 sec)

mysql>

After that I ran this code on the same DB:


comm.CommandText = "INSERT INTO test(id, name) VALUES ('1', 'Foo');INSERT INTO test(id, name) VALUES ('2', 'bar');";
comm.ExecuteNonQuery();

which gives me the following error:


+       base    {"ERROR [42000] [MySQL][ODBC 5.1 Driver][mysqld-5.1.51-community]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 test(id, name) VALUES ('2', 'bar')' at line 1"} System.Data.Common.DbException {System.Data.Odbc.OdbcException}


回答1:


Yes, ODBC does NOT support batch processing. (EDIT: See @Jean-Do's answer for a more up to date solution.)

But there is another option:

  1. Use the MySQL .NET Connector instead of ODBC.
  2. Then use the MySQL alternative INSERT statement: INSERT INTO test(id, name) VALUES ('1', 'Foo'), ('2', 'bar');.



回答2:


Batching is actually supported by MySQL ODBC driver v5+, you just need to click on the Details button of the ODBC control panel (if on Windows) and check the "Allow multiple statements" checkbox.

Alternatively, uses OPTIONS=67108864 on you odbc connection string.

More information here : http://dev.mysql.com/doc/refman/5.0/en/connector-odbc-configuration-connection-parameters.html




回答3:


It cannot handle batching (using ; to separate multiple statements) since this would require two way communication. I am afraid you have to do it in a loop and go to database multiple times.

In fact I have never been able to use batching with any managed provider.



来源:https://stackoverflow.com/questions/4144961/multiple-insert-statements-in-single-odbc-executenonquery-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!