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...
版权
作者:灵动生活