我有一个包含3列的数据库:FIRST_NAME,LAST_NAME和IMAGE。我总是收到错误"无效的列名称'第一列中的名称'。"我应该写第一个名字,然后单击一个按钮来显示姓氏和图像。我正在使用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);
}
}
}
感谢。
答案 0 :(得分:2)
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)