代码之家  ›  专栏  ›  技术社区  ›  beannshie223

C executenonquery错误

  •  0
  • beannshie223  · 技术社区  · 8 年前

    我试图将密码插入MS Access数据库,但在运行时出现以下错误,但由于某种原因,无法使executeNonQuery()函数正常工作。

    我正在尝试将文本框“password”中的字符串插入表“password”中的“password”列中。

    我得到这个错误:

    system.data.oledb.oledbException(0x80040e14):INSERT INTO语句中的语法错误。 在system.data.oledb.oledbcommand.executecommand文本错误处理(oledbhrult) 在系统中。 在system.data.oledb.oledbcommand.executecommandText(object&executesult) 在system.data.oledb.oledbcommand.executecommand(commandBehavior行为,对象执行结果) 在system.data.oledb.oledbcommand.executeReaderInternal(commandBehavior行为,字符串方法) 位于system.data.oledb.oledbcommand.executenonquery() 在insert_test.form1.pass_btn_处,单击c:\ users\mahir\source\repos\insert test\insert test\form1.cs中的(对象发送者,事件参数e):第43行

    这是我使用的代码:

    private OleDbConnection connection = new OleDbConnection();
    
    string database = Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location) + "\\password.accdb";
    
    connection.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + database + ";Jet OLEDB:Database Password=12345678;";
    
    
            try
            {
                connection.Open();
    
                OleDbCommand command = new OleDbCommand();
                command.Connection = connection;
                command.CommandText = "INSERT INTO Password ([password]) VALUES('" + password.Text + "')";
    
                command.ExecuteNonQuery();   // this is line 43
                MessageBox.Show("Success");
    
                connection.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(Convert.ToString(ex));
            }
    

    我的数据库名是一个名为“password.accdb”的MS Access 2010数据库,密码为“12345678”。

    下面是完整的代码: https://pastebin.com/D1xQ2LVg

    1 回复  |  直到 8 年前
        1
  •  4
  •   Erik A    8 年前

    密码是一个关键字。您已经正确地转义了列名,但没有转义表名。也需要方括号:

    INSERT INTO [Password] ([password]) VALUES('" + password.Text + "')"
    

    请注意,您的代码有两个主要缺陷:1。SQL注入有风险。2.它将密码存储为纯文本。对于实际使用的应用程序,这两个都是大的no,所以请读入参数化查询和散列密码。