-2
protected void submit_Click(object sender, EventArgs e)
{
    Label2.Text = Session["id"].ToString();
     SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString);
    SqlCommand cmd = con.CreateCommand();
    con.Open();
   
   string UpdateQuery = "Update register set name='" + name.Text + "'where email='" + Session["id"] + "'";
  
   SqlCommand cmd3 = new SqlCommand(UpdateQuery, con);
   cmd3.CommandType = CommandType.Text;
   con.Close();

}

}

I want to update name record using session for user profile in asp.net.

halfer
  • 19,824
  • 17
  • 99
  • 186

1 Answers1

1

Try like this:

using (SqlConnection conn =
    new SqlConnection(ConfigurationManager.ConnectionStrings["ConnString"].ToString()))
{
    string strSQL = "UPDATE register set [name] = @name " +
                    "WHERE email = @email";

    using (SqlCommand cmd = new SqlCommand(strSQL, conn))
    {
        cmd.Parameters.Add("@name", SqlDbType.NVarChar).Value = name.Text;
        cmd.Parameters.Add("@email", SqlDbType.NVarChar).Value = Session["id"].ToString();
        conn.Open();
        cmd.ExecuteNonQuery();
    }
}

The above will dispose/close the connection for you. And this will even close the connection if you have some error in the code.

The above also removes the messy "'" and concatenation in your code (easy to read, and maintain). And by using parameter's the code is also safe from injection.

hence:

enter image description here

Albert D. Kallal
  • 42,205
  • 3
  • 34
  • 51