更新数据的经典代码

private void UpdateUser()
        
{
            
if (Page.IsValid)
            
{
                
// Update the existing user
                SqlConnection con;
                
string sql;
                SqlCommand cmd;
                StringBuilder sb 
= new StringBuilder();
                ArrayList values 
= new ArrayList();

                
// Build the SQL string
                sb.Append("UPDATE [User] SET ");
                sb.Append(
"Login='{0}', Password='{1}', FirstName='{2}', ");
                sb.Append(
"LastName='{3}', PhoneNumber='{4}', Email='{5}'");

                
// Add required values to replace
                values.Add(txtLogin.Text);
                values.Add(txtPwd.Text);
                values.Add(txtFName.Text);
                values.Add(txtLName.Text);
                values.Add(txtPhone.Text);
                values.Add(txtEmail.Text);

                
// Add optional values directly
                if (txtAddress.Text != string.Empty)
                    sb.Append(
", Address='" + txtAddress.Text + "'");

                
if (txtMobile.Text != string.Empty)
                    sb.Append(
", CellNumber='" + txtMobile.Text + "'");

                
if (txtBirth.Text != string.Empty)
                
{
                    
// Pass date in ISO format YYYMMDD
                    DateTime dt = DateTime.Parse(txtBirth.Text);
                    sb.Append(
", DateOfBirth='");
                    sb.Append(dt.Year.ToString(
"d4"));
                    sb.Append(dt.Month.ToString(
"d2"));
                    sb.Append(dt.Day.ToString(
"d2"));
                    sb.Append(
"'");
                }


                sb.Append(
" WHERE UserID='{6}'");

                
// Get the UserID from the context.
                values.Add(Context.User.Identity.Name);
                sql 
= String.Format(sb.ToString(), values.ToArray());

                
// Connect and execute the query
                con = new SqlConnection("data source=(local)\\NetSdk;initial catalog=FriendsData;user id=sa");
                cmd 
= new SqlCommand(sql, con);
                con.Open();

                
bool doredirect = true;

                
try 
                
{
                    cmd.ExecuteNonQuery();
                }
 
                
catch
                
{
                    doredirect 
= false;
                    
this.lblMessage.Visible = true;
                    
this.lblMessage.Text = "Couldn't update your profile!";
                }

                
finally
                

                    con.Close();
                }


                
if (doredirect)
                    Server.Transfer(
"../Default.aspx");
            }

        }

原文地址:https://www.cnblogs.com/ahuang1118/p/172517.html