查询值和目标字段的数量不同

Sha*_*k G 5 c# ms-access oledbconnection winforms

我在将数据插入数据库时​​收到错误.

错误是:

"查询值和目标字段的数量不相同".

插入代码:

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();
Run Code Online (Sandbox Code Playgroud)

我究竟做错了什么?

San*_*hak 6

我想你只是错过了一些单引号。我看到您用起始和结束单引号将所有参数括起来。看到这个

还有一件事,当您传递大量参数时,为参数准备一个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());
Run Code Online (Sandbox Code Playgroud)

这样会更清晰,并且不会出现SQL 注入。