尝试在数据库中输入值时INSERT INTO语句中的语法错误

时间:2013-03-29 13:48:58

标签: c# asp.net database ms-access

您好我基本上正在创建一个注册页面。我收到错误说“INSERT INTO语句中的语法错误。”有时候我会得到一个错误,说连接是打开的或什么的。它之前在不同的表和不同的领域等工作......代码如下

public partial class Registration : System.Web.UI.Page
{
    static OleDbConnection con = new OleDbConnection(@"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:\New folder\Project 1.0\WebSite1\New Microsoft Office Access 2007 Database.accdb");
    OleDbDataAdapter ada = new OleDbDataAdapter();
    OleDbCommand cmd = new OleDbCommand();
    OleDbDataReader dr;
protected void Page_Load(object sender, EventArgs e)
{

}

protected void Button1_Click(object sender, EventArgs e)
{
    string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, Username, Password, Email, Address, City, Country, Zipcode)" +
         "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
    con.Open();
    cmd = new OleDbCommand(str, con);
    cmd.Parameters.AddWithValue("@p1", TextBox1.Text);
    cmd.Parameters.AddWithValue("@p2", TextBox2.Text);
    cmd.Parameters.AddWithValue("@p3", TextBox3.Text);
    cmd.Parameters.AddWithValue("@p4", TextBox4.Text);
    cmd.Parameters.AddWithValue("@p5", TextBox5.Text);
    cmd.Parameters.AddWithValue("@p6", TextBox6.Text);
    cmd.Parameters.AddWithValue("@p7", TextBox8.Text);
    cmd.Parameters.AddWithValue("@p8", TextBox12.Text);
    cmd.Parameters.AddWithValue("@p9", TextBox9.Text);
    cmd.Parameters.AddWithValue("@p10", TextBox11.Text);
    cmd.ExecuteNonQuery();
    con.Close();
}

}

我的mc访问表具有以下结构......

ID First_Name Last_name Phone_No用户名密码电子邮件地址城市国家邮政编码

有人可以帮帮我吗? :) 谢谢:))

3 个答案:

答案 0 :(得分:2)

您应该使用此查询:

  string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, [Username], [Password], [Email], [Address], City, Country, Zipcode)" +
     " values (@p1, @p2, @p3,@p4, @p5,@p6, @p7,@p8,@p9,@p10)";

答案 1 :(得分:1)

问题是由密码字引起的。这个词是reserved word in JET(MS-Access)
要在sql命令中使用该单词,您需要使用方括号将其封装。

当然,当您向查询添加参数时,应确保在查询中添加占位符所需的确切参数数量。
您有10个占位符(?),因此您需要10个参数,并且按照相应字段所需的确切顺序

所以,总结

string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, " + 
             "Username, [Password], Email, Address, City, Country, Zipcode)" +
             "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

答案 2 :(得分:0)

你错过了这一行的空间:

string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, Username, Password, Email, Address, City, Country, Zipcode)" +
     "values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";

应该是:

string str = "insert into User_Registeration (First_Name, Last_name, Phone_No, Username, Password, Email, Address, City, Country, Zipcode)" +
     " values (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";