代码无法使用用户记录检查

时间:2016-01-17 11:21:46

标签: c# asp.net

贝娄是不工作的代码,或者我是以错误的方式做的。

此代码在没有User record check condition的情况下工作,但是在该部分中它无效。任何人都可以指出问题吗?

protected void Reg_OnClick(object sender, EventArgs e)
{
    string HashedPass = PasswordHash.PasswordHash.CreateHash(Password.Text);

    string connStr = ConfigurationManager.ConnectionStrings["Account"].ConnectionString;
    using (SqlConnection conn = new SqlConnection(connStr))
    {
        conn.Open();

        string inst = "Select count (*) from UserCredinals where Email = @Email";
        SqlCommand cmd = new SqlCommand(inst, conn);

        cmd.Parameters.AddWithValue("@Email", Email.Text);
        int temp = Convert.ToInt32((String)cmd.ExecuteScalar().ToString());
        conn.Close();
        if (temp == 1)
        {

            Label2.Text = "User Exist please USe a Unique ID :";

        }
        else
        {
            conn.Open();

            using (SqlCommand cmdd = new SqlCommand("INSERT INTO UserCredinals (Name , Email , Phone , Password ) Values (@Name , @Email , @Phone , @Password);", conn))
            {
                try
                {
                    cmdd.Parameters.AddWithValue("@Name", Name.Text);
                    cmdd.Parameters.AddWithValue("@Email", Email.Text);
                    cmdd.Parameters.AddWithValue("@Phone", Phone.Text);
                    cmdd.Parameters.AddWithValue("@Password", HashedPass);
                    cmdd.ExecuteNonQuery();
                    conn.Close();
                    Response.Redirect("../Index.aspx");
                }
                catch
                {

                }
            }
        }
    }
}

1 个答案:

答案 0 :(得分:0)

为了解决您的代码问题:

1)将temp == 1替换为temp >= 1,以确保您不会遇到麻烦(如果您的表格中的电子邮件是唯一的,则不应该要求)

2)用

替换空catch
try (Exception exc)
{
   // log the error
   // place a breakpoint here to see if something is crashing when inserting
}  

提示:您可以使用finally来模仿OpenClose用法。类似的东西:

using (SqlConnection conn = new SqlConnection(connStr))
{
   try 
   {
      conn.Open();
      // all your logic here (SELECT, INSERT etc.)
   }
   catch (Exception exc)
   {
      // exception handling here
   }
   finally
   {
      if (conn.State == ConnectionState.Closed)
       conn.Close();
   }
}