我的项目中有一段代码,我在另一个 Using 块中包装了一个 Using 块,我想知道这是一个好习惯还是只是矫枉过正(请注意,我知道这是一个非常简单的代码片段,它是仅用于说明目的):
protected void Submit_Click(object sender, EventArgs e)
{
try
{
using (SqlConnection cn = new SqlConnection(ConfigurationManager.ConnectionStrings["RegConnectionString"].ConnectionString))
{
cn.Open();
string cmdStr = "SELECT COUNT(*) FROM REGISTRATION WHERE UserName ='" + this.TextBoxUN.Text + "' ";
using (SqlCommand selectUser = new SqlCommand(cmdStr, cn))
{
int temp = Convert.ToInt32(selectUser.ExecuteScalar().ToString());
if (temp == 0)
{
string insCmd = "Insert INTO REGISTRATION (UserName, Password, EmailAddress, FullName, Country) VALUES (@UserName, @Password, @EmailAddress, @FullName, @Country)";
using (SqlCommand insertUser = new SqlCommand(insCmd, cn))
{
try
{
insertUser.Parameters.AddWithValue("@UserName", this.TextBoxUN.Text);
insertUser.Parameters.AddWithValue("@Password", this.TextBoxPass.Text);
insertUser.Parameters.AddWithValue("@EmailAddress", this.TextBoxEA.Text);
insertUser.Parameters.AddWithValue("@FullName", this.TextBoxFN.Text);
insertUser.Parameters.AddWithValue("@Country", this.DropDownListCountry.SelectedItem.ToString());
insertUser.ExecuteNonQuery();
Response.Redirect("~/Login.aspx");
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}
else
{
Response.Write("User already Exists in Database");
}
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}