我有一個包含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