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.
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();
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#?
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?
If you are issuing an insert command, you should use
ExecuteNonQueryinstead ofExecuteReader.