检查数据库中是否已存在用户名和电子邮件

时间:2015-05-10 16:04:12

标签: c# asp.net

我正在尝试检查之前是否已使用过用户名和电子邮件。当用户尝试输入在显示错误消息之前已使用的用户名。与电子邮件相同。但是,当用户尝试使用不同的用户名和电子邮件注册时,会出现错误,提示myCommand.ExecuteNonQuery必须在rdr关闭之外,但我无法将其放在那里,因为它将无法被识别。

有人能解决这个问题吗?

protected void registerbutton_Click(object sender, EventArgs e)
{
    string newuser = regusername.Text;
    string newfirst = regfirst.Text;
    string newlast = reglast.Text;
    string newemail = regemail.Text;
    string newpass = regpass.Text;



    string connectionString = WebConfigurationManager.ConnectionStrings["photoconnection"].ConnectionString;

    SqlConnection myConnection = new SqlConnection(connectionString);


    myConnection.Open();



   string query1 = "SELECT * FROM users WHERE username=@nuser OR email=@nemail";




   SqlCommand myCommand1= new SqlCommand(query1, myConnection);
   myCommand1.Parameters.AddWithValue("@nuser", newuser);
   myCommand1.Parameters.AddWithValue("@nemail", newemail);


   SqlDataReader rdr = myCommand1.ExecuteReader();

    if (rdr.HasRows)
    {
       //when in read mode ask for data
        while (rdr.Read())
        {
            string uname = rdr["username"].ToString();
            string email = rdr["email"].ToString();

            if (regusername.Text == uname)
            {
                samevar.Text = "This Username already exists. Please choose another";

            }

            else if (regemail.Text == email)
            {
                samevar.Text = "This email already has an account associated with it. Please choose another";

            }


      }

      }
    else
    {
        string query = "INSERT INTO users (username, firstname, lastname, email, password, userrole) VALUES(@nuser, @nfirst, @nlast, @nemail, @npass, 'registered')";
        SqlCommand myCommand = new SqlCommand(query, myConnection);

        myCommand.Parameters.AddWithValue("@nuser", newuser);
        myCommand.Parameters.AddWithValue("@npass", newpass);
        myCommand.Parameters.AddWithValue("@nfirst", newfirst);
        myCommand.Parameters.AddWithValue("@nemail", newemail);
        myCommand.Parameters.AddWithValue("@nlast", newlast);

        regusername.Text = "";
        regpass.Text = "";
        regfirst.Text = "";
        reglast.Text = "";
        regemail.Text = "";

        myCommand.ExecuteNonQuery();
        myCommand.Dispose();

    }

    rdr.Close();

    myCommand1.ExecuteNonQuery();
    myCommand1.Dispose();






    myConnection.Close();

}

1 个答案:

答案 0 :(得分:1)

您无法在与开放数据阅读器关联的连接上执行任何命令。您必须关闭阅读器或使用其他连接。因为您的阅读器仅供开放阅读器使用。