下面提到的代码引发错误“插入声明中的语法错误”
这里我拿名字和号码字段有文字
否为自动编号(主键)
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/ppd/db1.mdb;Jet OLEDB:Database Password=techsoft");
da = new OleDbDataAdapter("select * from contacts", con);
DataSet ds = new DataSet();
da.Fill(ds, "contacts");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
OleDbConnection con;
OleDbDataAdapter da;
DataTable dt;
OleDbCommand cm;
string insertQuery = @"insert into contacts(names,number,no) Values (@names,@number,@no)";
cm = new OleDbCommand(insertQuery, con);
cm.Parameters.Add("@names", OleDbType.VarChar, 10, "names");
cm.Parameters.Add("@number", OleDbType.VarChar, 10, "number");
cm.Parameters.Add("@no", OleDbType.VarChar, 10, "no");
da.InsertCommand = cm;
private void button26_Click(object sender, EventArgs e)
{
da.Update(dt);
}
答案 0 :(得分:1)
您不能将文字放在数字类型字段中。如果“no”是自动编号,请不要给它一个值,它会自动递增。只需更改说:
的行string insertQuery = @"insert into contacts(names,number,no) Values (@names,@number,@no)";
到
string insertQuery = @"insert into contacts(names,number) Values (@names,@number)";
并删除显示
的行cm.Parameters.Add("@no", OleDbType.VarChar, 10, "no");
答案 1 :(得分:0)
不是自动编号,您无法在插入查询中将自动编号作为参数。
使用以下代码:
con = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:/ppd/db1.mdb;Jet OLEDB:Database Password=techsoft");
da = new OleDbDataAdapter("select * from contacts", con);
DataSet ds = new DataSet();
da.Fill(ds, "contacts");
dt = ds.Tables[0];
dataGridView1.DataSource = dt;
OleDbConnection con;
OleDbDataAdapter da;
DataTable dt;
OleDbCommand cm;
string insertQuery = @"insert into contacts([names],[number]) Values (@names,@number)";
cm = new OleDbCommand(insertQuery, con);
cm.Parameters.Add("@names", OleDbType.VarChar, 10, "names");
cm.Parameters.Add("@number", OleDbType.VarChar, 10, "number");
da.InsertCommand = cm;
注意:我刚刚删除了 参数列表。