我想插入一些數據到兩個MYSQL表中。 第二個表將第一個錶行ID存儲爲外鍵。 我有這個代碼工作正常,但它超級慢。什麼是使其更快的最好/最快的方式?如何插入多個MYSQL表C#快?
string ConnectionString = "server=localhost; password = 1234; database = DB ; user = Jack";
MySqlConnection mConnection = new MySqlConnection(ConnectionString);
mConnection.Open();
int index = 1;
for (int i = 0; i < 100000; i++)
{
string insertPerson = "INSERT INTO myentities(Name) VALUES (@first_name);"
+ "INSERT INTO secondtable(Id, Name,myentities) VALUES (@ID, @city, LAST_INSERT_ID());";
MySqlCommand command = new MySqlCommand(insertPerson, mConnection);
command.Parameters.AddWithValue("@first_name", "Jack");
command.Parameters.AddWithValue("@ID", i+1);
command.Parameters.AddWithValue("@city", "Frank");
command.ExecuteNonQuery();
command.Parameters.Clear();
}
我發現上的計算器問題之一下面的代碼,但它是將數據插入到一個表只,而不是應用,即通過外鍵連接的多個表。 這段代碼非常快,但我不確定如何使它能夠處理多個表。
public static void BulkToMySQL()
{
string ConnectionString = "server=192.168.1xxx";
StringBuilder sCommand = new StringBuilder("INSERT INTO User (FirstName, LastName) VALUES ");
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
List<string> Rows = new List<string>();
for (int i = 0; i < 100000; i++)
{
Rows.Add(string.Format("('{0}','{1}')", MySqlHelper.EscapeString("test"), MySqlHelper.EscapeString("test")));
}
sCommand.Append(string.Join(",", Rows));
sCommand.Append(";");
mConnection.Open();
using (MySqlCommand myCmd = new MySqlCommand(sCommand.ToString(), mConnection))
{
myCmd.CommandType = CommandType.Text;
myCmd.ExecuteNonQuery();
}
}
}
你發現的代碼也是痛苦的不安全。它實際上是乞求被黑客攻擊。不要使用它。 –