简体   繁体   English

C#将记录插入数据库表

[英]C# Insert Record into Database table

I have a database that contains a Customer table with the following columns : CustID, CustName, ICNumber, ContactNumber and Address.我有一个数据库,其中包含一个包含以下列的 Customer 表:CustID、CustName、ICNumber、ContactNumber 和 Address。 It is a service-based database.它是一个基于服务的数据库。

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();

The code compiles and runs.代码编译并运行。 The problem I am having is that the record is not added into the table after cmd.ExecuteNonQuery();我遇到的问题是在cmd.ExecuteNonQuery();之后没有将记录添加到表中cmd.ExecuteNonQuery(); is called.叫做。

Why is the record not showing up in the database table?为什么记录没有显示在数据库表中?

You forgot to close the quotes " on the insert command. It is nice to use try/catch to avoid problems with your insert, for sample:您忘记关闭插入命令上的引号" 。使用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();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM