我有一个包含3列的数据库:FIRST_NAME,LAST_NAME和IMAGE。我总是得到错误“无效列名”第一列的名称“。”我应该写出第一个名字并点击一个按钮来显示姓氏和图像。我正在使用C#,这是我当前的代码:从SQL数据库检索数据时出现“无效列名”错误?
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);
}
}
}
谢谢。
警告!永远不要连接输入字段的查询,因为您容易受到[SQL注入攻击](https://en.wikipedia.org/wiki/SQL_injection)的影响。改为使用参数化查询 – dotnetom