试图在数据库中输入值时,INSERT INTO语句出现语法错误
本文关键字:语句 INTO INSERT 错误 语法 数据库 输入 | 更新日期: 2023-09-27 18:06:34
嗨,我基本上是在创建一个注册页面。我得到一个错误说"语法错误在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用户名密码电子邮件地址城市国家邮编
有人能帮帮我吗?:)谢谢:)
您应该使用以下查询:
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)";
这个问题是由PASSWORD这个单词引起的。这个词是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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";
这一行少了一个空格:
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 (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)";