"invalid column name" 从 SQL 数据库检索数据时出错?

"invalid column name" error when retrieving data from SQL database?

我有一个包含 3 列的数据库:FIRST_NAME、LAST_NAME 和 IMAGE。我总是收到错误 "invalid column name 'the name from the first column'." 我应该写名字然后单击按钮以显示姓氏和图像。我正在使用 C#,这是我当前的代码:

        private void button_show_Click(object sender, EventArgs e)
    {
        try
        {
            string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME=" + this.firstname_textbox.Text + "";
            if (conn.State != ConnectionState.Open)
                conn.Open();
            command = new SqlCommand(sql, conn);
            SqlDataReader reader = command.ExecuteReader();
            reader.Read();
            if (reader.HasRows)
            {
                lastname_textbox.Text = reader[0].ToString();
                byte[] img = (byte[])(reader[1]);
                if (img == null)
                pictureBox1.Image = null;
                else
                {
                    MemoryStream ms = new MemoryStream(img);
                    pictureBox1.Image = Image.FromStream(ms);
                }

            }
            else
            {
                MessageBox.Show("This Name Does Not Exist");
            }
            conn.Close();
        }
        catch(Exception ex)
        {
            conn.Close();
            MessageBox.Show(ex.Message);
        }
    }
}

谢谢。

您的 WHERE 子句中有一个未加引号的字符串。

string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME=" + this.firstname_textbox.Text + "";

应该是:

string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='" + this.firstname_textbox.Text + "'";

您还应该知道,对 SQL 查询参数使用字符串连接是不好的做法,因为它会造成 SQL 注入漏洞。例如,假设 this.firstname_textbox.Text 的结果是:

';DELETE FROM Table_1 WHERE '1' = '1

这将导致变量 "sql" 为:

select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='';DELETE FROM Table_1 WHERE '1' = '1'

为避免此问题,请使用参数化查询 (https://msdn.microsoft.com/en-us/library/vstudio/bb738521%28v=vs.100%29.aspx)