InvalidOperationException on SqlCommand.ExecuteScalar()
本文关键字:ExecuteScalar SqlCommand on InvalidOperationException | 更新日期: 2023-09-27 18:24:57
我正在运行一个方法,该方法执行一个查询,然后在关闭连接之前尝试执行另一个查询。第一个查询执行良好,但第二个查询会导致:
SqlCommand.ExecuteScaler()方法出现InvalidOperationException。
我早些时候跑得很完美,但有些事情发生了变化,我似乎无法追踪。在执行查询之前,我正在测试连接是否已关闭或为null,但它不是null或已关闭。所以这个让我很困惑。有人知道发生了什么事吗?
正在执行的查询非常简单:
SELECT COUNT(*)
FROM browsers;
我已经在SQLServerManagementStudio中针对数据库进行了测试,它运行得很好。
internal static String[,] executeSelect(SqlConnection conn, Query query, Editor reference)
{
if (conn == null)
{
throw new System.ArgumentNullException("The SqlConnection parameter to method CSED.SQLServerdb.executeSelect(...) is null");
}
if (query == null)
{
throw new System.ArgumentNullException("The Query parameter to method CSED.SQLSererdb.executeSelect(...) is null");
}
String[,] data = null;
SqlCommand cmd = null;
SqlDataReader rdr = null;
SqlCommand cmd2 = null;
SqlCommand cmd3 = null;
try
{
Debug.WriteLine("SQLServerdb.executeSelect - query: " + query.ToString());
cmd = new SqlCommand(query.ToString(), conn);
rdr = cmd.ExecuteReader();
Field[] flds = query.Fields;
int columns = flds.Length;
//Debug.WriteLine("SQLServerdb.executeSelect -columns: " + columns);
int recordCount = 0;
List<TableRow> rows = new List<TableRow>();
TableRow tr = null;
while (rdr.Read())
{
tr = new TableRow();
recordCount++;
for (int i = 0; i < columns; i++)
{
tr.Add(DRExtension.GetStringOrNull(rdr, i));
}
rows.Add(tr);
}
data = convert2DArray(rows, columns);
//If reference to the class Editor is null then this Database class isn't being used
//in conjunction with the Editor class. Therefore, we don't need to calculate the number
//of records returned from the query.
if (reference != null && reference.IsUsingSSP)
{
bool flag = false;
int foundrows = 0;
//GET THE NUMBER OF RECORDS RETURNED BASED ON THE ORIGINAL QUERY.
String queryStr = "";
if (query.HaveWhereConditions)
{
queryStr = "SELECT COUNT(*) FROM " + query.GetParentTable() + query.prepareWhere(query.WhereConditions);
}
else
{
queryStr = "SELECT COUNT(*) FROM " + query.GetParentTable();
flag = true;
}
Debug.WriteLine("queryStr: " + queryStr);
if(conn.State == ConnectionState.Closed)
Debug.WriteLine("conn is closed");
if(conn == null)
Debug.WriteLine("conn is NULL");
cmd2 = new SqlCommand(queryStr, conn);
object result = cmd2.ExecuteScalar(); //This is where I get the error
if (result != null)
{
foundrows = Convert.ToInt32(result);
query.IFilteredTotal = foundrows;
}
//Debug.WriteLine("SQLServerdb.executeSelect - foundrows: " + foundrows);
//GET THE TOTAL NUMBER OF RECORDS IN THE TABLE.
if (flag == false)
{
queryStr = "SELECT COUNT(*) FROM " + query.GetParentTable();
//Debug.WriteLine("SQLServerdb.executeSelect - queryStr: " + queryStr);
cmd3 = new SqlCommand(queryStr, conn);
result = cmd3.ExecuteScalar();
if (result != null)
{
int r = Convert.ToInt32(result);
// Debug.WriteLine("SQLServerdb.executeSelect - Number of Records in the Table: " + r);
query.ITotal = r;
}
}
else
{
query.ITotal = foundrows;
}
}
}
catch (SqlException sqle)
{
String extra = "SQL Problem: " + sqle.Message + Constants.NEWLINE;
extra += "Vendor Error: " + sqle.ErrorCode + Constants.NEWLINE;
log.Error(extra + sqle.StackTrace);
Debug.WriteLine(extra + sqle.StackTrace);
}
catch (Exception e)
{
log.Error("SQLServerdb.executeSelect - query: " + query.ToString());
log.Error(e.StackTrace);
Debug.WriteLine(e.StackTrace);
}
finally
{
// Always make sure result sets and statements are closed,
// and the connection is returned to the pool
if(cmd != null)
{
cmd.Dispose();
cmd = null;
}
if (cmd2 != null)
{
cmd2.Dispose();
cmd2 = null;
}
if (cmd3 != null)
{
cmd3.Dispose();
cmd3 = null;
}
if (rdr != null)
{
rdr.Close();
rdr.Dispose();
rdr = null;
}
if (conn != null)
{
conn.Close();
conn.Dispose();
conn = null;
}
}
return data;
}//end executeSelect me
执行COUNT命令时,上一个SqlDataReader仍处于打开状态。这会导致一个错误,因为如MSDN 中所述
在使用SqlDataReader时,关联的SqlConnection为忙于为SqlDataReader提供服务,并且无法执行其他操作在SqlConnection上执行,而不是关闭它直到调用SqlDataReader的Close方法。例如在调用关闭之后才能检索输出参数
因此,如果这是导致错误的原因,那么在同一连接上发出另一个命令之前,应该添加一个rdr.Close
。(或者只需在连接字符串中添加MultipleActiveResultSets=True)
一个侧面,但非常重要的注意:你的体系结构创建字符串执行是有缺陷的。SQL注入对于每一个与数据库相关的代码来说都是一种危险的可能性。您应该需要在您的交易工具中添加参数化查询。