使用同一个 MySQL 连接插入多行? [英] Insert multiple row using the same MySQL connection?
问题描述
我想知道如何使用一个连接而不是打开和关闭多个连接将多行插入到 MySQL 数据库中.插入的数据来自 string[],所以我使用了 foreach 循环来获取每个值.
I was wondering how you can insert multiple rows into a MySQL database using one connection instead of opening and closing multiple connections. The data being inserted is coming from string[] so I used a foreach loop to get to each value.
这里是我当前的非工作 C# 代码:
Here my current non-working C# code:
string[] tempfin = table.Split(',');
string username = null;
connection.Open();
foreach (object hope in tempfin)
{
command.CommandText = "INSERT INTO ATable (Tried, Username) VALUES" + "('" + hope + "','" + username + "')";
command.ExecuteReader();
}
connection.Close();
我可以在 foreach 循环中打开和关闭连接,但是在插入大量行时这对我来说已经证明是不可靠的,那么有没有办法在 C# 中使用一个连接插入多行?
I could open and close the connection in the foreach loop but that has been proven unreliable to me when inserting a large amounts of rows, so is there a way insert multi rows using one connection in C#?
更新:没关系,我发现了我的问题.这是关于使用 command.ExecuteReader()
而不是 command.ExecuteNonQuery()
Update: Never mind, I found my problem. It was about using command.ExecuteReader()
instead of command.ExecuteNonQuery()
推荐答案
您发布的代码已经仅使用一个连接.我建议使用参数化查询而不是您正在使用的查询.
The code you posted is already using only one connection. I would suggest to use a parametrized query instead the one you are using.
为什么您的代码不起作用?你能用你得到的错误更新你的问题吗?
Why isn't your code working? Can you update your question with the error you're getting?
如果您要发出插入命令,则应使用 ExecuteNonQuery
而不是 ExecuteReader
.
If you are issuing an insert command, you should use ExecuteNonQuery
instead of ExecuteReader
.
这篇关于使用同一个 MySQL 连接插入多行?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!