数据未使用Windows应用程序插入数据库,但未显示任何错误

时间:2015-05-06 09:48:18

标签: asp.net

按钮单击代码

    String cs = null;
    SqlConnection scon = null;
    SqlCommand cmd = null;
    private void btnOk_Click(object sender,EventArgs e)
    {
            String name = txtBoxName.Text.ToString();
            String mobile = txtBoxMobile.Text.ToString();
            String address = txtBoxAddress.Text.ToString();
            String ty = null;
            if (radioButtonCow.Checked)
            {
                ty = radioButtonCow.Text.ToString();
            }
            else {
                ty = radioButtonBuffalo.Text.ToString();
            }
            int n = 0;
            using(scon = new SqlConnection(cs)){
                scon.Open();
                String query = "insert into new_customer(name,mobile,address,type) 
           values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";
                cmd = new SqlCommand(query, scon);
                n = cmd.ExecuteNonQuery();
            }
        }
        private void NewCustomer_Load(object sender, EventArgs e)
        {
            cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
        }
   }

当我运行此应用程序时,它成功运行而不显示任何错误,但它不会在表中插入任何记录。该表包含字段ID,名称,移动设备,地址和类型。 id是主键,它是一个标识字段。所有其他字段均为varchar类型。

为什么不在表格中插入数据?

2 个答案:

答案 0 :(得分:0)

您只需按照下面提到的方式传递参数,

 SqlConnection scon = new SqlConnection(cs);
 scon.Open();
 String query = "insert into new_customer values(@name,@mobile,@address,@type)";
 cmd = new SqlCommand(query, scon);
 cmd.Parameters.AddWithValue("@name",name);
 cmd.Parameters.AddWithValue("@name",mobile);
 cmd.Parameters.AddWithValue("@name",address);
 cmd.Parameters.AddWithValue("@name",ty);
 cmd.ExecuteNonQuery();
 scon.Close();

答案 1 :(得分:0)

尝试将type字段包装为[type]

String query = "insert into new_customer(name,mobile,address,[type]) values('" + name + "','" + mobile + "','" + address + "','" + ty + "')";