【发布时间】:2011-02-01 06:28:58
【问题描述】:
我是 C# 数据库交互的新手,我试图在 SqlCommand 和 SqlConnection 对象的帮助下在 SqlTransaction 的帮助下循环写入数据库中的 10000 条记录,并在 5000 之后提交。处理需要 10 秒。
SqlConnection myConnection = new SqlConnection("..Connection String..");
myConnection.Open();
SqlCommand myCommand = new SqlCommand();
myCommand.CommandText = "exec StoredProcedureInsertOneRowInTable Param1, Param2........";
myCommand.Connection = myConnection;
SqlTransaction myTrans = myConnection.Begintransaction();
for(int i=0;i<10000;i++)
{
mycommand.ExecuteNonQuery();
if(i%5000==0)
{
myTrans.commit();
myTrans = myConnection.BeginTransaction();
mycommand.Transaction = myTrans;
}
}
上面的代码在数据库中只给了我 1000 行写入/秒。
但是当我尝试在 SQL 中实现相同的逻辑并使用 SqlManagement Studio 在数据库上执行它时,它给了我 10000 写入/秒。 当我比较上述两种方法的行为时,它告诉我在使用 ADO.Net 执行时有大量的逻辑读取。
我的问题是: 1. 为什么ADO.Net执行中有逻辑读? 2. 交易是否有一些握手? 3. 为什么在管理工作室的情况下它们不可用? 4. 如果我想在 DB 上快速插入事务,那么方法是什么? .
关于数据库对象的更新信息
表格: tbl_FastInsertTest 没有主键,只有 5 个字段前三个是 int 类型(F1,F2,F3),后 2 个(F4,F5)是 varchar(30) 类型
存储过程:
create proc stp_FastInsertTest
{
@nF1 int,
@nF2 int,
@nF3 int,
@sF4 varchar(30),
@sF5 varchar(30)
}
as
Begin
set NoCOUNT on
Insert into tbl_FastInsertTest
{
[F1],
[F2],
[F3],
[F4],
[F5]
}
Values
{
@nF1,
@nF2,
@nF3,
@sF4,
@sF5,
} end
--------------------------------------------------------------------------------------
在 SSMS 上执行 SQL 块
--当我在 SSMS 上执行以下代码时,它每秒给我超过 10000 次写入,但是当我尝试在 ADO 上执行相同的 STP 时,它每秒给我 1000 到 1200 次写入
--同时读取无锁
begin trans
declare @i int
set @i=0
While(1<>0)
begin
exec stp_FastInsertTest 1,2,3,'vikram','varma'
set @i=@i+1
if(@i=5000)
begin
commit trans
set @i=0
begin trans
end
end
【问题讨论】:
标签: c# sql-server ado.net