INSERT查询错误:查询值和目标字段的数量不同

时间:2013-12-03 09:41:57

标签: c# asp.net sql ms-access

protected void Button1_Click1(object sender, EventArgs e)
{
    try
    {
        OleDbConnection con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=D:/WEB/App_Data/mydata.accdb");

        OleDbCommand com = new OleDbCommand("insert into player_reg (p_name,f_name,dob,pob,sex,marital,nation,address,address,state,mob,email,course,college,y_year,sports,voter) values ('" + TextBox1.Text + "', '" + TextBox2.Text + "','" + TextBox3.Text + "', '" + TextBox4.Text + "','" + TextBox5.Text + "', '" + TextBox6.Text + "','" + TextBox7.Text + "', '" + TextBox8.Text + "','" + TextBox9.Text+ "', '" + TextBox10.Text + "','" + TextBox11.Text + "', '" + TextBox12.Text+ "','" + TextBox13.Text+ "', '" + TextBox14.Text + "''" + TextBox15.Text + "', '" + TextBox16.Text + "')", con);
        con.Open();
        com.CommandType = CommandType.Text;
        com.ExecuteNonQuery();
        Response.Write("values inserted successfully");
        con.Close();
    }
    catch (Exception ex)
    {
        Response.Write(ex.ToString());
    }
}

3 个答案:

答案 0 :(得分:1)

您的查询中有adress次2次,请将其删除。

OleDbCommand com = new OleDbCommand(“insert into player_reg(p_name,f_name,dob,pob,sex,marital,nation, 的地址,地址下,状态,MOB,电子邮件,当然,学院, y_year,体育,选民)价值......

答案 1 :(得分:1)

列列表中有17个项目,但VALUES列表中只有16个项目。在列列表中,您重复address两次。

虽然我引起了您的注意,但通过“粘合”原始用户输入(textbox.Text值)构建SQL语句是非常糟糕的做法。您应该使用参数化查询。

con.Open();
OleDbCommand com = new OleDbCommand(
        "insert into player_reg (p_name, f_name, dob, pob, sex, marital, nation, address, state, mob, email, course, college, y_year, sports, voter)" +
        "values (?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?)", con);
com.Parameters.AddWithValue("?", TextBox1.Text);  // p_name
com.Parameters.AddWithValue("?", TextBox2.Text);  // f_name
com.Parameters.AddWithValue("?", TextBox3.Text);  // dob
// ...and so on...
com.Parameters.AddWithValue("?", TextBox16.Text);  // voter
com.ExecuteNonQuery();
con.Close();

答案 2 :(得分:0)

在您的查询中重复字段地址 - 列数必须等于“VALUES”子句中以','分隔的值的数量。