【问题标题】:Syntax error in INSERT INTO statement using OleDb使用 OleDb 的 INSERT INTO 语句中的语法错误
【发布时间】:2013-08-15 21:09:33
【问题描述】:

美好的一天。我正在尝试制作一个注册页面并将信息存储在数据库中。我使用 Microsoft Access 制作了数据库。我明白了:

INSERT INTO 语句中的语法错误

每次我按下“注册”按钮。我已经尝试在网上搜索类似的问题,并找到了一些类似“保留词”和“它必须是你的间距”的东西。我做了那些,它仍然给我错误。我错过了什么吗?

代码如下:

public void InsertRecord()
{
    OleDbCommand cmd = new OleDbCommand("INSERT INTO ElemData(StudentID, [Password], [Name], Age, Birthday, Address, FatherName, MotherName, " +
    "GuardianName, Class, Section, Email, PhoneNumber, MobileNumber) " + 
    "VALUES (@studentid, @password, @name, @age, @birth, @address, @father, @mother, @guardian, @classs, @section, @email, @phone, @mobile)", DBConnection.myCon);
    cmd.Parameters.Add("@studentid", OleDbType.VarChar).Value = Studentid;
    cmd.Parameters.Add("@password", OleDbType.VarChar).Value = Password;
    cmd.Parameters.Add("@name", OleDbType.VarChar).Value = Name;
    cmd.Parameters.Add("@age", OleDbType.VarChar).Value = Age;
    cmd.Parameters.Add("@birth", OleDbType.VarChar).Value = Birth;
    cmd.Parameters.Add("@address", OleDbType.VarChar).Value = Address;
    cmd.Parameters.Add("@father", OleDbType.VarChar).Value = Father;
    cmd.Parameters.Add("@mother", OleDbType.VarChar).Value = Mother;
    cmd.Parameters.Add("@guardian", OleDbType.VarChar).Value = Guardian;
    cmd.Parameters.Add("@classs", OleDbType.VarChar).Value = Classs;
    cmd.Parameters.Add("@section", OleDbType.VarChar).Value = Section;
    cmd.Parameters.Add("@email", OleDbType.VarChar).Value = Email;
    cmd.Parameters.Add("@phone", OleDbType.VarChar).Value = Phone;
    cmd.Parameters.Add("@mobile", OleDbType.VarChar).Value = Mobile;
    if (cmd.Connection.State == ConnectionState.Open)
    {
        cmd.Connection.Close();
    }
    DBConnection.myCon.Open();
    cmd.ExecuteNonQuery();
    DBConnection.myCon.Close();
}

【问题讨论】:

  • ElemData 表的列类型有哪些?
  • 他们目前是'TEXT'。

标签: c# ms-access ado.net oledb


【解决方案1】:

ClassSection 都是 reserved words。就像对保留字 [Password][Name] 所做的那样,将它们括在方括号中。

该页面包含 Allen Browne 的Database Issue Checker Utility 的链接。如果您有一个包含 Access 的 Office 版本,您可以下载该实用程序并使用它来检查您的 Access db 文件中的其他问题对象名称。

【讨论】:

  • 非常感谢!它现在起作用了。我想我不应该只搜索一个保留字列表,因为我发现的那个列表不包括这些。也感谢您的链接。由于我无法提供声誉,因此我将在这里发表评论以通知您它有效。
【解决方案2】:

如下修改你的sql

 OleDbCommand cmd = new OleDbCommand("INSERT INTO ElemData ([StudentID], [Password], [Name], [Age], [Birthday], [Address], [FatherName], [MotherName], " +
    "[GuardianName], [Class], [Section], [Email], [PhoneNumber], [MobileNumber]) " + 
    "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)", DBConnection.myCon);

OLE DB .NET 提供程序不支持传递命名参数 SQL 语句或存储过程的参数 当 CommandType 设置为 Text 时的 OleDbCommand。在这种情况下, 必须使用问号 (?) 占位符。

【讨论】:

  • 它仍然给我同样的错误。我们在课堂上使用过这段代码,虽然使用的表只有 4 列,但它仍然有效。这里的 ElemData 大约有 48 列,其中大部分是“Subject1”、“Subject2”等。现在我想知道有 48 列的表是否会导致这种情况,因为我在代码中看到了一些列空白。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多