[英]Should I execute every query or single query?
I'm trying to Insert multiple records to table using ado.net
, and print id
inserted.我正在尝试使用ado.net
向表中插入多条记录,并插入打印id
。
My code is like this:我的代码是这样的:
List<string> listQuery = new List<string>()
{
"INSERT INTO Students (Name) VALUES ('student1');SELECT @@Identity;",
"INSERT INTO Students (Name) VALUES ('student2');SELECT @@Identity;",
"INSERT INTO Students (Name) VALUES ('student3');SELECT @@Identity;",
};
using (SqlConnection connection = new SqlConnection(_connectionString))
{
try
{
connection.Open();
using (SqlCommand command = new SqlCommand())
{
command.Connection = connection;
foreach (var myQuery in listQuery)
{
command.CommandText = myQuery;
int id = Convert.ToInt32((decimal)command.ExecuteScalar());
Console.WriteLine("Inserted: " + id);
}
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
//Close and dispose
connection.Close();
}
}
I wondering, whether should I execute every command like that?我想知道,我是否应该执行每个这样的命令? Or concatenate all query and execute just a times?.还是连接所有查询并只执行一次?
If I should execute one times.如果我应该执行一次。 How can i get all id
of records inserted?如何获取插入的所有记录id
?
Don't go like this, and DON'T call database in ANY loop.不要像这样 go ,也不要在任何循环中调用数据库。
For resolving your problem, you should write stored procedure that take a DataTable as input of your student list ( tutorial ) or use JSON string as input.为了解决您的问题,您应该编写将 DataTable 作为学生列表( 教程)的输入的存储过程,或者使用JSON 字符串作为输入。 In that stored procedure you use OUTPUT
clause to retrieve id: OUTPUT INSERTED.id
.在该存储过程中,您使用OUTPUT
子句检索 id: OUTPUT INSERTED.id
。 On C# code, you only need ExecuteReader
to get all id.在 C# 代码上,您只需要ExecuteReader
即可获取所有 id。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.