SqlDataReader.ExecuteReader();即使提供了所有参数,也返回null对象

问题描述 投票:0回答:2
SqlConnection connection = Connect();

SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = sprocName;
command.Connection = connection;
//loop through the dictionary
foreach (string key in paramList.Keys)
{
        command.Parameters.AddWithValue(key, paramList[key]);
}
SqlDataReader dataReader = command.ExecuteReader();

我正在尝试从数据库读取数据,当我传递相同的参数并执行SP然后我得到了正确的结果。但是这里SqlDataReader dataReader = command.ExecuteReader();当我检查(dataReader.HasRows)它返回false!

c# sql-server sqldatareader sqlconnection executereader
2个回答
0
投票

你的密钥是否包含'@',例如,如果密钥参数名称EmployeeId需要添加如下参数

commnad.Parameters.AddWithValue('@EmployeeId', 1);

0
投票

执行up_GetAtt @ pageNumber = 1,@ pagesize = 10,@ PID = 1000,@ DeID = NULL,@ DEName = NULL,@ SortByColumn ='ReleaseDate',@ SortOrder ='DESC'这是我传递的参数

您需要将C#空值转换为DBNull

SqlConnection connection = Connect();

SqlCommand command = new SqlCommand();
command.CommandType = CommandType.StoredProcedure;
command.CommandText = sprocName;
command.Connection = connection;
//loop through the dictionary
foreach (string key in paramList.Keys)
{
        command.Parameters.AddWithValue(key, paramList[key] == NULL? DBNull.Value : paramList[key]);
}
SqlDataReader dataReader = command.ExecuteReader();

鉴于缺乏帮助您更好的信息,请检查常见错误

  • 过程和参数名称中的错别字
  • 使用CommandType.StoredProcedure发送查询:sprocName值必须只是“up_GetAtt”,包含EXEC字或参数是一个常见的错误。
  • 检查值类型,您的paramList应该是一个字典,并且您放在该列表中的项的值类型应该与sql等效类型匹配,并非所有类型都具有隐式转换。
  • 检查paramList项的可空性,使用nullable int和datetime
  • 检查参数名称是否以@开头
  • 省略参数并不意味着它是null,除非您的存储过程定义将其默认为null
  • 省略过程定义中没有默认值的参数
  • 不必要的引用值,你发送参数值,它不是一个concat
© www.soinside.com 2019 - 2024. All rights reserved.