【问题标题】:C# parameter is not valid SQLC# 参数无效 SQL
【发布时间】:2016-10-04 08:07:30
【问题描述】:

我有从我观看的教程中复制的代码,我们的代码在教程中非常相似。

当演示者运行代码时,它运行正常,但是当我尝试运行与教程中相同的代码时,我收到错误“参数无效”。

请帮忙

    private void Viewbutton_Click(object sender, EventArgs e)
    {
        conection.Open();

        string sqlQuery = "select studnum, course, f_name, l_name, color_image from table3 where studnum='" + textBox1.Text + "'";

        cmd = new SqlCommand(sqlQuery, conection);

        SqlDataReader dataread = cmd.ExecuteReader();
        dataread.Read();

        if (dataread.HasRows)
        {
            lblstudnum.Text = dataread[0].ToString();
            lblcourse.Text = dataread[1].ToString();
            lblfname.Text = dataread[2].ToString();
            lbllname.Text = dataread[3].ToString();
            byte[] images = (byte[])dataread[4];

            if(images==null)
            {
                pictureBox1.Image = null;
            }
            else
            {
                MemoryStream mstreem = new MemoryStream(images);
                pictureBox1.Image = Image.FromStream(mstreem);
            }
        }
        else
        {
            MessageBox.Show("this data not available");
        }
    }

错误行是

pictureBox1.Image = Image.FromStream(mstreem);

【问题讨论】:

  • 您应该在WHERE 子句中使用参数化查询而不是串联。
  • 哪个教程建议使用字符串连接来构建 sql 查询?使用参数化查询。
  • 我希望你们的学生都没有进入0'; DROP TABLE table3; --
  • @andrewfaz 那是一个糟糕的教程。阅读What is SQL injection
  • @andrewfaz:然后忘记“教程”并从MSDN开始,尤其是Commands and Parameters部分。

标签: c# sql-server


【解决方案1】:

最好使用参数查询和列名,而不是使用[0],[1]等。内存流由数据阅读器使用。所以你应该使用如下,提供一个有效的图像保存在数据库

    var con = new SqlConnection("the connection string to database");
    con.Open();

    SqlCommand cmd = new SqlCommand(@"sql query",con);
    byte[] images = null;
    using (SqlDataReader dataread = cmd.ExecuteReader())
    {
        if (dataread.Read())
        {
            //lblstudnum.Text = dataread[0].ToString();
            //lblcourse.Text = dataread[1].ToString();
            //lblfname.Text = dataread[2].ToString();
            //lbllname.Text = dataread[3].ToString();
            images = (byte[])dataread["color_image"];// column name is recommended
        }
    }
    con.Close();
    if (images == null)
    {
        pictureBox1.Image = null;
    }
    else
    {
        MemoryStream mstreem = new MemoryStream(images);
        pictureBox1.Image = Image.FromStream(mstreem);
    }

【讨论】:

  • 我试试这些,它说“连接属性尚未初始化”
  • @andrewfaz:找到解决方案了吗
【解决方案2】:

可能不是有效的图像。向您的程序添加一些调试代码(或设置watch),它将输出内存流的长度及其前几个字节。确保长度符合您的预期。确保文件前缀存在(如果有),例如位图文件有一个two-letter alphanumeric prefix。确保它没有被截断。确保它是allowed file format。问题可能是您教师的数据库中有数据,而您的数据库中没有。

【讨论】:

  • 是的,图像可能无效,但我保存在 varbinary 中,但现在我将其替换为图像数据类型,但仍然是相同的错误
  • 我不是指数据类型,我指的是数据内容。
  • 也许作为故障排除措施,您可以将程序更改为save the image to a file,然后尝试使用 MS Paint 打开它。如果打不开,说明数据有问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多