这段代码中的错误是什么?

时间:2011-08-19 02:32:11

标签: database sql-server-2005

我想在富文本框

中显示行
private void button1_Click(object sender, EventArgs e) {
        SqlConnection con = new SqlConnection("Data Source=MOSTAFA\\SQLEXPRESS;Initial Catalog=company;Integrated Security=True");
        SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"')",con);
        con.Open();
        SqlDataReader read = com.ExecuteReader();
        if (read.Read())
            richTextBox1.Text = "id" + read[0].ToString();
        else
            label3.Text=("The client didn't found");
    }

2 个答案:

答案 0 :(得分:2)

生成的查询中存在错误。你有一个没有开头的右括号。你拥有的那条线会产生:

select * from data where id='sometest')

将从SQL Server产生语法错误。

请改为尝试:

SqlCommand com = new SqlCommand("select * from data where id='"+textBox1.Text+"'",con);

答案 1 :(得分:0)

在该SQL语句中有一个额外的括号。

但更重要的是,你正在为SQL Injection留下空位。要解决这个破坏性且易于避免的问题,请使用参数化查询。