我在项目中有一段代码,在一个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);
}
}
}
IDisposable
的内容,请使用using
并尽快进行处理。 - Tim Schmelter