簡體   English   中英

什么是“未提供參數化查詢...。”錯誤?

[英]What is “The parameterized query … which was not supplied.” error?

我在遇到錯誤

"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();

使用AddWithValue而不是Add方法。

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

您應該在命令中使用@來提供參數。

SonerGö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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM