您好我正在Visual Studio 2012 Express中创建基本表单。我使用Microsoft Access 2012作为数据库。我的问题是当我按下提交按钮时我没有任何反应。
INSERT INTO语句中的语法错误。 System.Data.OleDb.OleDbErrorCollection
我的代码如下。请帮我解决这个问题。
protected void Button1_Click(object sender, EventArgs e)
{
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd = con.CreateCommand();
string text = "INSERT INTO TEST (Number, Amount) VALUES (?, ?)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("@Number", txtAmount.Text);
cmd.Parameters.AddWithValue("@Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
答案 0 :(得分:2)
OleDbCommand
不支持命名参数。您必须按所需顺序添加参数。
//Code above
con.Open();
cmd.Parameters.Add(txtAmount.Text);
cmd.Parameters.Add(txtOrder.Text);
cmd.ExecuteNonQuery();
//Code below
答案 1 :(得分:2)
除了一次性物品周围缺少using statement之外,你的代码是正确的,但真正的问题是NUMBER这个词。这是reserved keyword for MSAccess 用方括号括起来。
string text = "INSERT INTO TEST ([Number], Amount) VALUES (?, ?)";
但是,如果仍有可能,我建议您更改该列名称。这个问题会变得非常烦人。
protected void Button1_Click(object sender, EventArgs e)
{
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
using(OleDbConnection con = new OleDbConnection(conString))
using(OleDbCommand cmd = con.CreateCommand())
{
string text = "INSERT INTO TEST ([Number], Amount) VALUES (?, ?)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("@Number", txtAmount.Text);
cmd.Parameters.AddWithValue("@Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
答案 2 :(得分:2)
您对@Number
和@Amount
使用Number
和Amount
个变量,但未在查询中写入这些值。
?
不在asp.net(c#)中。所以你要混合这两个。
protected void Button1_Click(object sender, EventArgs e)
{
string conString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\admin\Desktop\del\SHAFI\db.accdb";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd = con.CreateCommand();
string text = "INSERT INTO TEST (Number, Amount) VALUES (@Number, @Amount)";
cmd.CommandText = text;
try
{
con.Open();
cmd.Parameters.AddWithValue("@Number", txtAmount.Text);
cmd.Parameters.AddWithValue("@Amount", txtOrder.Text);
cmd.ExecuteNonQuery();
}
catch (OleDbException ex)
{
txtAmount.Text = "Sorry";
Response.Write(ex.Message.ToString() + "<br />" + ex.Errors.GetType());
}
}
答案 3 :(得分:1)
您应该使用:
string text = "INSERT INTO TEST (Number, Amount) VALUES (@Number, @Amount)";
而不是:
INSERT INTO TEST (Number, Amount) VALUES (?, ?)