来自C#和Access子句的语法错误

时间:2014-07-06 17:32:43

标签: c# sql database

我一直收到此运行时错误syntax error in from clause。我尝试在访问中使用我的SQL查询,看起来没问题。

这是我的代码,我正在使用带有文本框和按钮的C#窗体

            OleDbConnection conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\Users\Misry27\Documents\Visual Studio 2010\Projects\Inventory\Inventory\bin\Debug\Inventory.mdb");
            OleDbCommand cmd = new OleDbCommand("select * from Employee where username = '" + this.tbUsername.Text + "' and password = '" + this.tbPassword.Text + "';", conn);
            OleDbDataReader dr;
            conn.Open();
            dr = cmd.ExecuteReader();

            int count = 0;
            while (dr.Read())
            {
                count = count + 1;
            }
            if (count == 1)
            {
                MessageBox.Show("Username or Password is correct");
            }
            else
            {
                MessageBox.Show("Username or Password Incorrect");
            }
            conn.Close();

1 个答案:

答案 0 :(得分:2)

正如上面的评论中所解释的那样,PASSWORD是一个保留的关键字,当用于从net执行的查询时,需要用方括号括起来。

通常的建议如下。使用参数化查询来避免解析问题和sql注入,使用围绕一次性对象的using语句。

using(OleDbConnection conn = new OleDbConnection(a correct connection string here))
using(OleDbCommand cmd = new OleDbCommand(@"select * from Employee 
                                            where username = ? AND [Password] = ?", conn);
{

    conn.Open();
    cmd.Parameters.AddWithValue("@p1", this.tbUsername.Text);
    cmd.Parameters.AddWithValue("@p2", this.tbPassword.Text);
    using(OleDbDataReader dr = cmd.ExecuteReader())
    {
       .....
    }
}