首页 文章

使用OleDb的INSERT INTO语句中的语法错误

提问于
浏览
6

美好的一天 . 我正在尝试创建一个注册页面并将信息存储在数据库中 . 我使用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();
}

2 回答

  • 2

    ClassSection 都是reserved words . 将它们包含在方括号中,就像保留字 [Password][Name] 一样 .

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

  • 7

    改变你的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);
    

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

相关问题