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.

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

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

如果你认为此文章有用,请点击底端的【推荐】让其他人也了解此文章,

img_2c313bac282354945ea179a807d7e70d.jpg

本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。

 

相关文章
|
2月前
|
SQL 存储 数据库
SQL NOT NULL
【11月更文挑战第14天】
59 6
|
8月前
|
SQL 分布式计算 数据库
Spark SQL
Spark SQL
85 1
|
SQL
update panelNo SQL
巧妙的更新panelNo的SQL
55 0
|
SQL 数据采集 分布式计算
基于Spark SQL的数据探索
基于Spark SQL的数据探索
|
SQL 数据库管理
【SQL系列】处理NULL
【SQL系列】处理NULL
163 0
|
SQL Oracle 关系型数据库
一个需求的三种实现(sql)
一个需求的三种实现(sql)
一个需求的三种实现(sql)
|
存储 SQL 分布式计算
深入理解SPARK SQL 中HashAggregateExec和ObjectHashAggregateExec以及UnsafeRow
深入理解SPARK SQL 中HashAggregateExec和ObjectHashAggregateExec以及UnsafeRow
784 0
深入理解SPARK SQL 中HashAggregateExec和ObjectHashAggregateExec以及UnsafeRow
|
SQL 分布式计算 大数据
Spark SQL玩起来
标签(空格分隔): Spark [toc] 前言 Spark SQL的介绍只包含官方文档的Getting Started、DataSource、Performance Tuning和Distributed SQL Engine部分。
9501 0
|
SQL 分布式计算 Spark
|
SQL
[20171110]sql语句相同sql_id可以不同吗
[20171110]sql语句相同sql_id可以不同吗.txt --//提一个问题,就是sql语句相同sql_id可以不同吗? --//使用dbms_shared_pool.
1299 0