写List<;对象>;到数据库
本文关键字:数据库 gt 对象 lt List | 更新日期: 2023-09-27 17:59:14
请解释如何使WriteToBase()
方法更快,或者如何在不调用每个insert
的情况下进行大容量插入。
class MyClass
{
public int a;
public int b;
public int c;
}
void main()
{
List<MyClass> mc = new List<MyClass>();
mc.Add(new MyClass()); //example
mc.Add(new MyClass());
WriteToBase(mc);
}
void WriteToBase(List<MyClass> mc)
{
//Create Connection
string sqlIns = "INSERT INTO table (name, information, other) VALUES (@name, @information, @other)";
SqlCommand cmdIns = new SqlCommand(sqlIns, Connection);
for (int i = 0; i < mc.Count; i++)
{
cmdIns.Parameters.Add("@name", mc[i].a);
cmdIns.Parameters.Add("@information", mc[i].b);
cmdIns.Parameters.Add("@other", mc[i].c);
cmdIns.ExecuteNonQuery();
}
}
有什么想法吗?
您当前正在多次访问数据库。所有插入应该只有1次命中。
试试这个代码:
void WriteToBase(List<MyClass> mc)
{
//Create Connection
using (TransactionScope scope = new TransactionScope())
{
string sqlIns = "INSERT INTO table (name, information, other)
VALUES (@name, @information, @other)";
SqlCommand cmdIns = new SqlCommand(sqlIns, Connection);
for(int i=0;i<mc.Count;i++)
{
cmdIns.Parameters.Add("@name", mc[i].a);
cmdIns.Parameters.Add("@information", mc[i].b);
cmdIns.Parameters.Add("@other", mc[i].c);
cmdIns.ExecuteNonQuery();
}
scope.Complete();
}
}
使用SqlBulkCopy。它使您能够高效地使用来自另一个源的数据大容量加载SQL Server表。
private static void WriteToBase(IEnumerable<MyClass> myClasses)
{
var dataTable = new DataTable();
dataTable.Columns.Add("name", typeof(string));
dataTable.Columns.Add("information", typeof(string));
dataTable.Columns.Add("other", typeof(string));
foreach (var myClass in myClasses)
{
var row = dataTable.NewRow();
row["name"] = myClass.name;
row["information"] = myClass.information;
row["other"] = myClass.other;
dataTable.Rows.Add(row);
}
using var connection = new SqlConnection(Constants.YourConnectionString);
connection.Open();
using var bulk = new SqlBulkCopy(connection) {DestinationTableName = "table" };
bulk.WriteToServer(dataTable);
}
void WriteToBase(List<MyClass> mc)
{
//Create Connection
using (TransactionScope scope = new TransactionScope())
{
string sqlIns = "INSERT INTO table (name, information, other)
VALUES (@name, @information, @other)";
SqlCommand cmdIns = new SqlCommand(sqlIns, Connection);
for(int i=0;i<mc.Count;i++)
{
cmdIns.Parameters.AddWithValue("@name", mc[i].a);
cmdIns.Parameters.AddWithValue("@information", mc[i].b);
cmdIns.Parameters.AddWithValue("@other", mc[i].c);
cmdIns.ExecuteNonQuery();
cmdIns.Parameters.Clear();
}
scope.Complete();
}
}