我有一个名为Entry
声明如下:
class Entry{
string Id {get;set;}
string Name {get;set;}
}
然后是一个接受多个这样的方法Entry
使用 ADO.NET 插入数据库的对象:
static void InsertEntries(IEnumerable<Entry> entries){
//build a SqlCommand object
using(SqlCommand cmd = new SqlCommand()){
...
const string refcmdText = "INSERT INTO Entries (id, name) VALUES (@id{0},@name{0});";
int count = 0;
string query = string.Empty;
//build a large query
foreach(var entry in entries){
query += string.Format(refcmdText, count);
cmd.Parameters.AddWithValue(string.Format("@id{0}",count), entry.Id);
cmd.Parameters.AddWithValue(string.Format("@name{0}",count), entry.Name);
count++;
}
cmd.CommandText=query;
//and then execute the command
...
}
}
我的问题是:我应该继续使用上述发送多个插入语句的方式(构建一个巨大的插入语句及其参数字符串并通过网络发送它),还是应该保持开放连接并发送单个插入语句对于每个Entry
像这样:
using(SqlCommand cmd = new SqlCommand(){
using(SqlConnection conn = new SqlConnection(){
//assign connection string and open connection
...
cmd.Connection = conn;
foreach(var entry in entries){
cmd.CommandText= "INSERT INTO Entries (id, name) VALUES (@id,@name);";
cmd.Parameters.AddWithValue("@id", entry.Id);
cmd.Parameters.AddWithValue("@name", entry.Name);
cmd.ExecuteNonQuery();
}
}
}
你怎么认为?两者之间的Sql Server性能会有差异吗?我还应该注意任何其他后果吗?