asp.net无法更新数据库

时间:2010-03-31 21:11:01

标签: asp.net

string ConnectionString = WebConfigurationManager.ConnectionStrings["dbnameConnectionString"].ConnectionString;
SqlConnection myConnection = new SqlConnection(ConnectionString);

myConnection.Open();
try
{
    string qry = "UPDATE customers SET firstname=@firstname WHERE cid=1";
    SqlCommand insertQuery = new SqlCommand(qry, myConnection);
    insertQuery.Parameters.Add(new SqlParameter("@firstname", txtFirstname.Text));
    insertQuery.ExecuteNonQuery();

    myConnection.Close();
}
catch (Exception ee)
{

}

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

您可能想尝试的一些代码清理(您应该处理IDisposable对象):

string ConnectionString = // ...
using (var connection = new SqlConnection(ConnectionString))
using (var command = connection.CreateCommand())
{
    connection.Open();
    command.CommandText = "UPDATE customers SET firstname = @firstname WHERE cid=1";
    command.Parameters.AddWithValue("@firstname", txtFirstname.Text);
    var rowsUpdated = command.ExecuteNonQuery();
}