InvalidOperationException未处理 - 请说明

时间:2017-11-09 14:44:32

标签: c# ms-access

我正在创建一个连接到Access的软件的用户登录,我继续得到相同的错误,突出显示行'i =(int)command.ExecuteScalar();'说...

System.Data.dll中发生未处理的“System.Data.OleDb.OleDbException”类型异常 附加信息:查询表达式中的语法错误(缺少运算符)'Username ='MGRjs'和密码'Candy''。

    private void LoginButton_Click(object sender, EventArgs e)
    {
        OleDbConnection connection = new OleDbConnection(@"Provider = Microsoft.ACE.OLEDB.12.0; Data Source = F:\Loughborough\3rd Year\Individual Project\StockManagement system\Database.accdb");
        OleDbCommand command = new OleDbCommand();

        int i = 0;
            if (IDtbx.Text == string.Empty)
            {
                MessageBox.Show("Please log in");
            }
            command = new OleDbCommand("select count(*)from NewUser where Username= '" + IDtbx.Text + "' AND Password '" + PSWtbx.Text + "'", connection);

            if (connection.State == ConnectionState.Closed)
            {
                connection.Open();
                i = (int)command.ExecuteScalar();
            }

            connection.Close();
            if (i > 0) 
            {
                MainSystem mainForm = new MainSystem();
                mainForm.FormClosed += new FormClosedEventHandler(Login_FormClosed);
                mainForm.Show();
                this.Hide();
                LoginError.Visible = false;
            }

            else
            {
                LoginError.Visible = true;
            }

    }

1 个答案:

答案 0 :(得分:0)

您的SQL错误,因此您的数据库正在引发错误。

select count(*)from NewUser where Username= 'blablalbla' AND Password 'whatever'

您错过了密码和值之间的=

BTW,您的代码很容易出现SQL注入,请考虑使用参数化查询以避免安全漏洞,