c# – 查询值和目标字段的数量不同
作者:互联网
我在将数据插入数据库时收到错误.
错误是:
“Number of query values and destination fields are not the same”.
插入代码:
OleDbConnection vconn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Mutyyba\\Documents\\Database1.accdb");
vconn.Open();
string name = textBox1.Text;
string address = textBox3.Text;
int rollno = Convert.ToInt32(textBox2.Text);
string vquery = "insert into Table1 values(@vname,@vrollno,@vaddress)";
OleDbCommand vcomm = new OleDbCommand(vquery, vconn);
vcomm.Parameters.AddWithValue("@vname", name);
vcomm.Parameters.AddWithValue("@vrollno", rollno);
vcomm.Parameters.AddWithValue("@vaddress", address);
vcomm.ExecuteNonQuery();
MessageBox.Show("your record has been recorded sucessfully!");
vconn.Close();
我究竟做错了什么?
解决方法:
我想你只是错过了一些单引号.我看到你已经用起始和结束单引号括起了所有参数.见this
还有一件事,因为你传递了很多参数,为参数准备了一个SqlCommand对象.
有关详细信息,请参见msdn.
做这样的事情:
SqlCommand comm = new SqlCommand("INSERT INTO table VALUES (@txtsno, @txtdesg, @txtbasic)", connection);
comm.Parameters.AddWithValue("@txtsno", txtsno.Text.Trim());
comm.Parameters.AddWithValue("@txtsno", txtdesg.Text.Trim());
comm.Parameters.AddWithValue("@txtsno", txtbasic.Text.Trim());
这将更加清晰,并且不会出现SQL Injection.
标签:c,winforms,ms-access,oledbconnection 来源: https://codeday.me/bug/20190521/1147259.html