图像中的更新语句错误

时间:2018-04-02 05:57:39

标签: c# .net sql-server sql-update

private void btnupdate_Click(object sender, EventArgs e)
{
    byte[] img1 = File.ReadAllBytes(@"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");

    try
    {
        if (txtfno.Text == "" && txtslab.Text == "")
        {
            MessageBox.Show("Update not possible");
        }
        else
        {
            cnn.Open();
            cmd3.CommandText = "update Slab set indi = @img1 where s_flatno = @s_flatno and s_name = @s_name";

            cmd3.Parameters.AddWithValue("@indi",img1);
            cmd3.Parameters.AddWithValue("@s_flatno", txtfno.Text);
            cmd3.Parameters.AddWithValue("@s_name", txtslab.Text);

            cmd3.ExecuteNonQuery();
        }
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
    finally
    {
        cnn.Close();
    }
}

在这段代码中,我正在更新位置indi中的图像,并且我在字节中设置了一个新的img1。按下更新时我收到错误

  

必须声明标量变量@ img1

2 个答案:

答案 0 :(得分:1)

您已在SQL语句中命名变量@img1,但在声明变量时命名为@indi

请注意,处理DBConnection时的最佳做法是using语句中的局部变量,并且在向命令添加参数时最好使用Add的重载之一AddWithValue。有关详细信息,请参阅Can we stop using AddWithValue() already?

以下是代码的改进版本:

private void btnupdate_Click(object sender, EventArgs e)
{

    if (txtfno.Text == "" && txtslab.Text == "")
    {
        MessageBox.Show("Updation not possible");
    }
    else
    {
        try
        {

            byte[] img1 = File.ReadAllBytes(@"C:\Users\Admin\Desktop\Final Project Bridger\Bridger\Bridger\Images\20green.png");

            var sql = "update Slab set indi=@indi where s_flatno=@s_flatno and s_name=@s_name";
            // I'm assuming SQL Server based on the error message
            using(var cnn = new SqlConnection(connectionString))
            {
                using(var cmd = new SqlCommand(sql, cnn))
                {
                    cmd.Parameters.Add("@indi", SqlDbType.VarBinary).Value = img1;
                    cmd.Parameters.Add("@s_flatno", SqlDbType.VarChar).Value = txtfno.Text;
                    cmd.Parameters.Add("@s_name", SqlDbType.VarChar).Value = txtslab.Text;
                }
                cnn.Open();
                cmd3.ExecuteNonQuery();
            }
        catch (Exception ex)
        {
            MessageBox.Show(ex.ToString());
        }
    }
}

答案 1 :(得分:0)

您的代码存在一个小问题。你还没有传递@ img1参数。你发送它作为@indi。在sql查询字符串中将@ img1更改为@indi或在添加参数语句中将@indi更改为@ img1:

cnn.Open();
cmd3.CommandText = "update Slab set indi=@indi where s_flatno=@s_flatno and s_name=@s_name";
cmd3.Parameters.AddWithValue("@indi",img1);
cmd3.Parameters.AddWithValue("@s_flatno", txtfno.Text);
cmd3.Parameters.AddWithValue("@s_name", txtslab.Text);
cmd3.ExecuteNonQuery();