我搜索我的数据时显示语法错误
string sql = "Select Name,Father_name,NIC_No,Image from Admform WHERE Member_ID=" + textBoxmember.Text + "";
if (cn.State != ConnectionState.Open)
cn.Open();
command = new SqlCommand(sql, cn);
SqlDataReader reader = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBoxname.Text = reader[0].ToString();
textBoxfname.Text = reader[1].ToString();
textBoxnic.Text = reader[2].ToString();
byte[] img = (byte[])(reader[3]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("This is does not exist.");
}
cn.Close();
答案 0 :(得分:1)
首先,您应该使用Parameterized Query
,因此您的查询将变为
string sql = "Select Name,Father_name,NIC_No,Image from Admform WHERE Member_ID=@memid";.
using (SqlConnection connection = new SqlConnection(/* connection info */))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
var memidParam = new SqlParameter("memid", SqlDbType.Int);
memidParam.Value = textBoxmember.Text;
command.Parameters.Add(memidParam);
var results = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBoxname.Text = reader[0].ToString();
textBoxfname.Text = reader[1].ToString();
textBoxnic.Text = reader[2].ToString();
byte[] img = (byte[])(reader[3]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("This is does not exist.");
}
}
}
或Parameters.AddWithValue
string sql = "Select Name,Father_name,NIC_No,Image from Admform WHERE Member_ID=@memid";.
using (SqlConnection connection = new SqlConnection(/* connection info */))
{
connection.Open();
using (SqlCommand command = new SqlCommand(sql, connection))
{
command.Parameters.AddWithValue("@memid", textBoxmember.Text);
command.Parameters.Add ("@p_Date", SqlDbType.DateTime).Value = DateTimePicker1.Value;
var results = command.ExecuteReader();
reader.Read();
if (reader.HasRows)
{
textBoxname.Text = reader[0].ToString();
textBoxfname.Text = reader[1].ToString();
textBoxnic.Text = reader[2].ToString();
byte[] img = (byte[])(reader[3]);
if (img == null)
pictureBox1.Image = null;
else
{
MemoryStream ms = new MemoryStream(img);
pictureBox1.Image = Image.FromStream(ms);
}
}
else
{
MessageBox.Show("This is does not exist.");
}
}
}
使用using
可以帮助您在代码块完成后自动进行破坏或处置。因此需要手动关闭或处理对象。
答案 1 :(得分:1)
让我总结一下问题,列Member_ID
可能不是一个整数,你试图传递没有引号的文本,如果你传递任何字符串值,它必须包含在一对{{1 }}。但实际上这可以被认为是一种错误的方法,因为它通过Injection为攻击者打开了一道大门。所以我强烈要求你使用Paramaterized查询:
'