【问题标题】:What is "The parameterized query ... which was not supplied." error?什么是“未提供的参数化查询……”。错误?
【发布时间】:2013-09-30 06:36:47
【问题描述】:

我遇到了一个错误

"The parametrized query '(@blue nvarchar(4000))SELECT blueBallImage FROM CorrespondingBal' expects the parameter '@blue',
which was not supplied."

我正在做一个 HttpHandler。

我想从数据库中检索图像。我的代码如下。

public void ProcessRequest (HttpContext context) {
    string image = context.Request.QueryString["image"];

    SqlConnection con = new SqlConnection(@"Data Source=localhost;Initial Catalog=MyCloudGames;Integrated Security=True"); 
    SqlCommand cmd = new SqlCommand("SELECT blueBallImage FROM CorrespondingBall WHERE objective = blue", con); 
    cmd.CommandType = CommandType.Text; 
    cmd.Parameters.Add("blue", image); 

    con.Open(); 
    byte[] ballImage = (byte[])cmd.ExecuteScalar(); 
    con.Close(); 

    context.Response.ContentType = "image/png"; 
    context.Response.OutputStream.Write(ballImage, 78, ballImage.Length - 78); 
}

错误发生在

byte[] ballImage = (byte[])cmd.ExecuteScalar();

【问题讨论】:

    标签: c# httphandler


    【解决方案1】:

    使用AddWithValue 代替Add 方法。

    SqlCommand cmd = new SqlCommand("SELECT blueBallImage FROM CorrespondingBall WHERE objective = @blue", con); 
    cmd.CommandType = CommandType.Text; 
    cmd.Parameters.AddWithValue("@blue", image);
    

    您应该在命令中为您的参数提供@

    Soner Gönül,图像为空。我该如何纠正?

    因此,如果您的 imagenull,您应该返回 DBNull.Value。您不能在必需参数上传递 null。您可以使用方法作为替代方法;

    SqlCommand cmd = new SqlCommand("SELECT blueBallImage FROM CorrespondingBall WHERE objective = @blue", con); 
    cmd.CommandType = CommandType.Text; 
    cmd.Parameters.AddWithValue("@blue", CheckForDbNull(image));
    
    ...
    
    public static object CheckForDbNull(object value)
    {
       if(value == null)
       {
           return DBNull.Value;
       }
    
       return value;
    }
    

    【讨论】:

    • 您好,谢谢!但是,它不起作用。同样的错误仍然发生。
    • @LiuJiaHui 检查我更新的问题。请记住使用@blue 而不是blue
    • @LiuJiaHui 你确定你的image 不为空吗?用调试器检查。
    • @LiuJiaHui 更新了我的问题。
    猜你喜欢
    • 2019-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多