[英]Insert multiple row using the same MySQL connection?
我想知道如何使用一個連接而不是打開和關閉多個連接將多行插入MySQL數據庫。 插入的數據來自string []所以我使用foreach循環來獲取每個值。
這是我目前的非工作C#代碼:
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#中使用一個連接插入多行?
更新:沒關系,我發現了我的問題。 它是關於使用command.ExecuteReader()
而不是command.ExecuteNonQuery()
您發布的代碼已經只使用了一個連接。 我建議使用參數化查詢而不是您正在使用的查詢。
你的代碼為何不起作用? 你能用你得到的錯誤更新你的問題嗎?
如果要發出insert命令,則應使用ExecuteNonQuery
而不是ExecuteReader
。
你可以用MySQL做這樣的事情:
INSERT INTO ATable (X, Y) VALUES (1, 2), (3, 4), (5, 6), (7, 8)
這將插入4行。 因此,只需更新代碼以構建單個語句,並執行該語句,如果您擔心連續執行多個INSERT
語句。
不確定,但我嘗試的其他方式最終導致修復mysql錯誤,如“現有連接必須關閉”
這很可能是因為您正在使用ExecuteReader
而不是ExecuteNonQuery
正如Pablo Santa Cruz指出的那樣。
在那里,清理了一下。 是的,它只使用那個連接。
string[] tempfin = table.Split(',');
string username = null;
try
{
connection.Open();
SQLParameter parUserName = new SqlParameter("@username", System.Data.SqlDbType.VarChar,100);
if(username != null) parUserName.Value = username; else parUserName.Value = DBNull.Value;
SQLParameter parHope = new SqlParameter("@hope", System.Data.SqlDbType.VarChar,256);
command.Parameters.Add(parUserName);
command.Parameters.Add(parHope);
command.CommandText = "INSERT INTO ATable (Tried, Username) VALUES (@hope,@username)";
foreach (string hope in tempfin)
{
parHope.Value = hope;
command.ExecuteNonQuery();
}
}
finally{
if (connection.State != System.Data.ConnectionState.Closed)
connection.Close();
if(command != null)
command.Dispose();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.