最有效的方式将行插入MySQL数据库 [英] Most efficient way to insert Rows into MySQL Database
问题描述
我已经读了很多有关的问题,但我找不到一个足够快。我认为有更好的方法来插入很多行到一个MySQL数据库
I've read a lot of questions about that but i couldn't find one that is fast enough. I think there are better ways to insert a lot of rows into a MySQL Database
我用下面的code插入到100K我的MySQL数据库内数据:
I use the following code to insert 100k into my MySQL-Database:
public static void CSVToMySQL()
{
string ConnectionString = "server=192.168.1xxx";
string Command = "INSERT INTO User (FirstName, LastName ) VALUES (@FirstName, @LastName);";
using (MySqlConnection mConnection = new MySqlConnection(ConnectionString))
{
mConnection.Open();
for(int i =0;i< 100000;i++) //inserting 100k items
using (MySqlCommand myCmd = new MySqlCommand(Command, mConnection))
{
myCmd.CommandType = CommandType.Text;
myCmd.Parameters.AddWithValue("@FirstName", "test");
myCmd.Parameters.AddWithValue("@LastName", "test");
myCmd.ExecuteNonQuery();
}
}
}
这花费10万行约40秒。我怎样才能使这个快还是有点更有效率?
This takes for 100k rows about 40 seconds. How can i make this faster or a little more efficient?
可能会更快通过一个DataTable / DataAdapter的或一次插入多行:
Might be faster to insert multiple rows via a DataTable/DataAdapter or at once:
INSERT INTO User (Fn, Ln) VALUES (@Fn1, @Ln1), (@Fn2, @Ln2)...
由于安全问题,我无法将数据加载到一个文件,并MySQLBulkLoad它。
Due to security issues i can't load the data into a file and MySQLBulkLoad it.
推荐答案
这是我的多个插入 - code。 100K的行插入了而不是40秒才检查第3秒。!
here is my "multiple inserts"-code. The insertion of 100k rows took instead of 40 seconds only 3 seconds!!
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();
}
}
}
这reults到
INSERT INTO User (FirstName, LastName) VALUES ('test','test'),('test','test'),... ;
这篇关于最有效的方式将行插入MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!