C#将记录插入数据库表

时间:2015-11-02 12:41:53

标签: c# database

我有一个包含Customer表的数据库,其中包含以下列:CustID,CustName,ICNumber,ContactNumber和Address。它是一个基于服务的数据库。

string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;

SqlConnection con = new SqlConnection(localdb);
con.Open();
SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID,CustName,ICNumber,ContactNumber,Address)values(@CustID,@CustName,@ICNumber,@ContactNumber,@Address)", con);

                        cmd.Parameters.AddWithValue("@CustID", txtCustID.Text);
                        cmd.Parameters.AddWithValue("@CustName", txtCustName.Text);
                        cmd.Parameters.AddWithValue("@ICNumber", txtICNum.Text);
                        cmd.Parameters.AddWithValue("@ContactNumber", txtContact.Text);
                        cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
                        cmd.ExecuteNonQuery();
                        con.Close();

代码编译并运行。我遇到的问题是,在调用cmd.ExecuteNonQuery();后,记录不会添加到表中。

为什么记录没有显示在数据库表中?

1 个答案:

答案 0 :(得分:1)

您忘记在insert命令上关闭引号"。最好使用try/catch来避免插入问题,例如:

string localdb = ConfigurationManager.ConnectionStrings["DatabaseConnectionString"].ConnectionString;

try
{
    SqlConnection con = new SqlConnection(localdb))


    con.Open();

    SqlCommand cmd = new SqlCommand("INSERT INTO Customer(CustID, CustName, ICNumber, ContactNumber, Address) VALUES (@CustID, @CustName, @ICNumber, @ContactNumber, @Address)", con);
    cmd.Parameters.AddWithValue("@CustID", txtCustID.Text);
    cmd.Parameters.AddWithValue("@CustName", txtCustName.Text);
    cmd.Parameters.AddWithValue("@ICNumber", txtICNum.Text);
    cmd.Parameters.AddWithValue("@ContactNumber", txtContact.Text);
    cmd.Parameters.AddWithValue("@Address", txtAddress.Text);
    cmd.ExecuteNonQuery();
}
catch
{
    // some errors 
}
finally 
{
    if (con.State == ConnectionState.Open)
       con.Close();
}