I have a database with 3 columns on it: FIRST_NAME, LAST_NAME, and IMAGE. I always get the error "invalid column name 'the name from the first column'." I am supposed to write the first name and click a button to show the last name and the image. I am using C#, this is my current code:
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);
}
}
}
Thanks.
You have an unquoted string in your WHERE clause.
string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME=" + this.firstname_textbox.Text + "";
should be:
string sql = "select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='" + this.firstname_textbox.Text + "'";
You should also know that using string concatenation for SQL query parameters is bad practice as it creates a SQL Injection vulnerability. For example, imagine the result if this.firstname_textbox.Text was:
';DELETE FROM Table_1 WHERE '1' = '1
This would result in the variable "sql" being this:
select LAST_NAME,IMAGE from Table_1 where FIRST_NAME='';DELETE FROM Table_1 WHERE '1' = '1'
To avoid this problem, use parameterized queries ( https://msdn.microsoft.com/en-us/library/vstudio/bb738521%28v=vs.100%29.aspx )
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.