请告诉我如何更快地制作下一个代码(我的意思是方法WriteToBase)。
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();
}
}
}
有什么想法吗?
答案 0 :(得分:10)
您目前正在多次访问数据库。所有插页应该只有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();
}
}
答案 1 :(得分:0)
使用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);
}
答案 2 :(得分:-4)
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();
}
}