【发布时间】:2010-06-04 09:45:06
【问题描述】:
我有一个名为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会不会有性能差异?还有其他我应该注意的后果吗?
【问题讨论】:
-
感谢您的所有建议!我会接受@Giorgi 的回答,因为它或多或少地回答了原始问题
-
可以在SQl server中使用user-definedtable类型将DataTable传递给SQL serverfourthbottle.com/2014/09/…
标签: c# sql-server-2005 ado.net multiple-insert