SQL 查询表示未提供参数,但已将其添加到 SqlCommand 对象中
我有一个存储过程,它有一个名为 UserName 的参数,在我后面的代码中,我有一个 SqlCommand 对象,我使用 Add 方法将参数添加到其中。但由于某种原因,当命令对象尝试运行 ExecuteReader 方法时,它会引发异常。我完全不知所措,不知道为什么它不识别该参数。在运行 ExecuteReader 方法之前,我设置了一个断点,以便我可以确认命令对象确实包含正在设置的参数,这是正确的。我知道当参数未添加到命令对象但在实际存储过程中硬编码时,存储过程确实返回正确的数据。以下是 catch 块中给出的异常消息。我还将粘贴我的代码和存储过程的第一部分。我将非常感谢在这个问题上的任何帮助,因为我已经尝试了许多不同的方法但无济于事。提前致谢。
异常消息
过程或函数“someStoredProcedure”需要参数“@UserName”,但未提供该参数。
代码隐藏
private DataTable GetLossMitData(string code, DateTime? start, DateTime? end)
{
DataTable results = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["asdf"].ConnectionString;
string userName = String.Empty;
try
{
using (SPSite site = new SPSite(ConfigurationManager.AppSettings["someName"]))
{
using (SPWeb web = site.OpenWeb())
{
userName = web.CurrentUser.Email.ToString();
}
}
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
using (SqlCommand command1 = new SqlCommand("someStoredProcedure", connection1))
{
command1.Parameters.Add(new SqlParameter("@UserName", userName));
command1.Parameters.Add(new SqlParameter("@ProductCode", code));
SqlDataReader dr = command1.ExecuteReader(CommandBehavior.CloseConnection);
results.Load(dr);
}
connection1.Close();
}
}
catch (Exception ex)
{
}
return results;
}
存储过程
@UserName nvarchar(256),
@ProductCode nvarchar(256),
@StartDate nvarchar(256) = '1/1/1900',
@EndDate nvarchar(256) = '12/30/2012'
AS
BEGIN
SET NOCOUNT ON;
Declare @UserID int
Select @UserID = Users.UserID
from Users
where Users.Email = @UserName
I have a stored procedure that has a parameter called UserName and in my code behind I have a SqlCommand object that I add the parameters to with the Add method. But for some reason when the command object tries to run the ExecuteReader method, it throws an exception. I am totally at a loss and have no idea why it's not recognizing the parameter. Before the ExecuteReader method is run I have a break point set so I can confirm the command object does contain the parameters being set, which is true. I know the stored procedure does return the correct data when the parameters are not added to the command object, but are hard coded in the actual stored procedure. Below is the exception message that is given in the catch block. I will also paste my code and first part of stored procedure. I would greatly appreciate any help in this issue, seeing that I have tried many different approaches to no avail. Thanks in advance.
Exception Message
Procedure or function 'someStoredProcedure' expects parameter '@UserName', which was not supplied.
Code Behind
private DataTable GetLossMitData(string code, DateTime? start, DateTime? end)
{
DataTable results = new DataTable();
string connectionString = ConfigurationManager.ConnectionStrings["asdf"].ConnectionString;
string userName = String.Empty;
try
{
using (SPSite site = new SPSite(ConfigurationManager.AppSettings["someName"]))
{
using (SPWeb web = site.OpenWeb())
{
userName = web.CurrentUser.Email.ToString();
}
}
using (SqlConnection connection1 = new SqlConnection(connectionString))
{
connection1.Open();
using (SqlCommand command1 = new SqlCommand("someStoredProcedure", connection1))
{
command1.Parameters.Add(new SqlParameter("@UserName", userName));
command1.Parameters.Add(new SqlParameter("@ProductCode", code));
SqlDataReader dr = command1.ExecuteReader(CommandBehavior.CloseConnection);
results.Load(dr);
}
connection1.Close();
}
}
catch (Exception ex)
{
}
return results;
}
Stored Procedure
@UserName nvarchar(256),
@ProductCode nvarchar(256),
@StartDate nvarchar(256) = '1/1/1900',
@EndDate nvarchar(256) = '12/30/2012'
AS
BEGIN
SET NOCOUNT ON;
Declare @UserID int
Select @UserID = Users.UserID
from Users
where Users.Email = @UserName
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
尝试确保命令类型设置为存储过程。
Try making sure that the command type is set to stored procedure.
如果“userName”变量的值为 null,您将收到此异常。
如果 null 有效,则将“DBNull.Value”传递给数据库:
You will get this exception if the value of your 'userName' variable is null
If null is valid, then pass 'DBNull.Value' to the db instead:
这将强制 ExecuteReader 执行 exec,而不是仅仅尝试将其作为平面命令。
This will force the ExecuteReader to perform the exec instead of just trying it as a flat command.
默认情况下,
CommandText
属性需要包含完整的 SQL 命令,而不仅仅是存储过程的名称。您可以通过设置
SqlCommand
的CommandType
属性到StoredProcedure
。或者,您可以通过将
CommandText
更改为"someStoredProcedure @UserName, @ProductCode"
来显式传递参数;这是一个完整的 SQL 语句,将与Text
的默认CommandType
一起使用。编辑:我刚刚尝试过,在不将
CommandType
设置为StoredProcedure
(他没有这样做)的情况下获取该错误消息的唯一方法是如果CommandText
是EXEC someStoredProcedure
。传递null
参数会产生不同的错误。By default, the
CommandText
property needs to contain a complete SQL command, not just the name of the stored procedure.You can change this by to set the
SqlCommand
'sCommandType
property toStoredProcedure
.Alternatively, you could explicitly pass the parameters, by changing the
CommandText
to"someStoredProcedure @UserName, @ProductCode"
; this is a complete SQL statement and will work with the defaultCommandType
ofText
.EDIT: I just tried it, and the only way to get that error message without setting
CommandType
toStoredProcedure
(which he did not do) is ifCommandText
isEXEC someStoredProcedure
. Passing anull
parameter gives a different error.ADO.NET 提供了在.NET 平台上运行数据库操作的类,并使用多种方法处理结果。重要的部分之一是在数据库和数据库中执行相关命令。检索它的结果。 ADO.NET为这部分操作提供了SqlCommand类。
根据您的选择和设计代码时,有几种方法可以管理它。我相信最好的方法是在数据库中编写存储过程在您的代码中执行它们。为了编写正确的代码,您需要在 SqlCommand 对象中设置以下部分:
1 - Connection(提供与数据库的连接)
2 - CommandType(检测您选择的执行类型,如简单文本或存储过程)
3 - CommandText(基于 CommandType) ,它可以是存储过程的名称或完整的数据库命令文本)
如果您的命令包含参数(存储过程或简单文本),则必须将它们添加到SqlCommand的Parameters对象中。现在您可以在数据库上运行命令检索结果。
例如,要读取数据,您可以选择 ExecuteReader() 方法(还有其他方法,但也有一些差异);对于 DML 操作,您可以使用 SqlCommand 对象的 ExecuteNonQuery() 方法。
如果您以正确的方式进行操作,它应该可以正常工作而不会出现问题。
注意:这些类位于 System.Data.SqlClient 命名空间中针对 Sql Server 进行了优化。对于其他供应商,您可以在 System.Data.Common 包(现代 .NET)中使用类似的类。
ADO.NET provides classes to run the DB operations in .NET platform and handle the results with several methods. One the important parts is executing related command in database & retrieve the result of it. ADO.NET provides SqlCommand class for this part of operations.
Based on your choose & design of code, there are several ways to manage this. I believe the best way is writing Stored Procedures in your database & execute them in your code. For making the correct code you need to set these parts in your SqlCommand object:
1 - Connection (provide the connection to database)
2 - CommandType (detect your choose for executing type like simple text or stored procedure)
3 - CommandText (based on CommandType, it can be the name of stored procedure or full database command text)
If your command includes parameters (stored procedure or simple text), you have to add them in Parameters object of SqlCommand. Now you can run your command on database & retrieve the result.
For reading data for example you can choose ExecuteReader() method (there are another ways with some differences too) and for DML operations you can use ExecuteNonQuery() method of SqlCommand object.
If you did it in right way, it should work properly without problem.
Note: these classes are in System.Data.SqlClient namespace & optimized for Sql Server. For another vendors you can use similar classes in System.Data.Common package (modern .NET).