遇到The SqlParameter is already contained by another SqlParameterCollection.

Msdn论坛:

http://social.msdn.microsoft.com/Forums/zh-CN/vblanguage/thread/39519dab-bf7f-4050-8eba-fede0d46869e

以下是一网友的文章:

The SqlParameter is already contained by another SqlParameterCollection.

以下是从国外网站找到的 解决办法

Yesterday, I came across a odd bug while debugging some code for a proof of concept application.

The code itself was simple connecting to the database, executing two queries using different SqlCommand objects, but the same SqlParameter collection and returning the results to the user.

The method itself look two parameters, a SQL query as a string and a SQL Parameter[]. I would then simply add the parameters to the SqlCommand:

SqlCommand sqlCmd = new SqlCommand(sql, sqlConn);
sqlCmd.Parameters.AddRange(queryParams);

     

After executing I would close the connection, then code would do some other stuff and a different query would be executed but using the same parameter collection.  In theory, there is no reason why this wouldn't work however the code was throwing an exception with the error "The SqlParameter is already contained by another SqlParameterCollection."  How odd, I had closed the connection and it shouldn't be referred so I should be able to add it.

Turns out, or at least I think, that the garage collection isn't kicking in quick enough and so the reference is still alive.  Quick fix was to clear the parameters on the SqlCommand object after execution.

sqlCmd.Parameters.Clear();

Tripped me up for a little bit so I thought I would post.  Carry on...

版权

作者:灵动生活

出处:http://www.cnblogs.com/ywqu

转载于:https://www.cnblogs.com/goldarch/archive/2011/08/09/2131749.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值