SqlDataReader无法正常工作,它会跳过检查用户名的部分

时间:2013-04-27 23:55:57

标签: c# visual-studio-2010 sqldatareader

我正在开发一个拥有1个客户端和1个服务器的项目。我还创建了一个类库,我在其中放置代码,而不是在服务器和客户端将此类库作为参考。所以我通过创建类的对象来调用客户端的方法。 它工作得非常好......直到现在!

在类库中我有一个名为Check()的方法,它检查用户名是否已经存在(当尝试注册时,以及其他一些东西。但问题是它从数据库检查用户名的步骤是Skipped !!我不知道为什么,它没有向我显示错误原因。唯一出现的错误是由于跳过步骤而尝试将相同的用户名插入数据库时​​出现的错误。

这是类库代码:

    bool busy = false;
    bool empty = false;
    bool notSame = false;
    bool completed = false;

public void Check(string a1, string b2, string c3, string d4, string e5, string f6)
    {
        SqlConnection con = new SqlConnection(@"Data Source=TALY-PC;Initial Catalog=TicTacToe;Integrated Security=True");

        SqlCommand cmd = new SqlCommand("SELECT * FROM tblUsers", con);

        if (con.State.Equals(ConnectionState.Open))
        {
            return;
        }
        else
        {
            con.Open();
        }

        SqlDataReader dr = cmd.ExecuteReader();

        while (dr.Read())
        {

            if (dr["Username"].ToString() == d4)
            {
                busy = true;
            }
            else if (a1 == "" || b2 == "" || c3 == "" || d4 == "" || e5 == "" || f6 == "")
            {

                empty = true;

            }
            else if (e5 != f6)
            {
                notSame = true;
                return;
            }
            else
            {
                dr.Close();
                SqlCommand cmd1 = new SqlCommand("INSERT INTO tblUsers (Name, LastName, email, Username, Password) VALUES ('" + a1 + "', '" + b2 + "', '" + c3 + "', '" + d4 + "', '" + e5 + "')", con);

                cmd1.ExecuteNonQuery();

                completed = true;
            }
        }

跳过的部分是这部分:

if (dr["Username"].ToString() == d4)
            {
                busy = true;
            }

我不知道为什么不检查这部分?

以下是客户的代码:

HttpChannel chan = new HttpChannel();

    Tic obj = (Tic)Activator.GetObject(typeof(Tic), "http://127.0.0.1:9050/MyMathServer");

private void RegisterForm_Load(object sender, EventArgs e)
    {
        ChannelServices.RegisterChannel(chan);
    }

 private void Button1_Click(object sender, EventArgs e)
   {
 obj.Check(textBoxX1.Text, textBoxX2.Text, textBoxX3.Text, textBoxX4.Text, textBoxX5.Text, textBoxX6.Text);
        label8.Text = obj.getUseri();
        if (obj.getBusy() == true)
        {
            MessageBox.Show("This username is already Taken, please choose another username");

            obj.setBusy();

        }
        else if (obj.getEmpty() == true)
        {
            MessageBox.Show("Please fill all the fields!");
            obj.setEmpty();
        }
        else if (obj.getNotSame() == true)
        {
            MessageBox.Show("Passwords don't match!!");
            textBoxX5.Text = "";
            textBoxX6.Text = "";
            obj.setNotSame();
        }
        else if (obj.getCompleted() == true)
        {
            MessageBox.Show("Registration was completed successfully. Please close the window and Log Int ");
            textBoxX1.Text = "";
            textBoxX2.Text = "";
            textBoxX3.Text = "";
            textBoxX4.Text = "";
            textBoxX5.Text = "";
            textBoxX6.Text = "";
            obj.setCompleted();

        }
  }

有人可以告诉我为什么不检查用户名?

1 个答案:

答案 0 :(得分:1)

我不完全理解你的代码。我可以做一些简单的观察:

  • 首先:使用您的连接和datareader的using。无论发生什么(例外等),using都会关闭它们。
  • 为变量使用更好的名称。 a1直到f6没有任何意义。给他们有意义的名字让我们更容易阅读...所以...如果真的不知道为什么e5必须等于f6。
  • 同样适用于您的文本框。
  • 语句if (a1 == "" || b2 == "" || c3 == "" || d4 == "" || e5 == "" || f6 == """)在while循环中,但由于这些值永远不会改变,您可能会考虑将它们移出循环。
  • 同样适用于if (e5 != f6)行。
  • 检查连接是否已打开。但是这个连接刚刚创建。它怎么可以开放?如果它会开放......它只会在没有做任何事情的情况下返回?
  • 如果您达到条件(e5 != f6)且条件为真,则返回。但是你没有关闭连接就这样做了。
  • 如果所有参数均为"",但数据库中没有记录,则不会设置empty。这是设计吗?

试试这段代码:

public enum Result
{
    Busy,
    Empty,
    NotSame,
    Completed
}

public Result Check(string name, string lastName, string eMail, string userName, string password1, string password2)
{
    // You should check with String.IsNullOrEmpty(...), not just an empty string.
    if (name == "" || lastName == "" || eMail == "" || userName == "" || password1 == "" || password2 == "")
        return Result.Empty;

    if (password1 != password2)
        return Result.NotSame;

    using(SqlConnection con = new SqlConnection(@"Data Source=TALY-PC;Initial Catalog=TicTacToe;Integrated Security=True"))
    {
        SqlCommand cmd = new SqlCommand("SELECT COUNT(*) FROM tblUsers WHERE UserName=@0", con);
        cmd.Parameters.AddWithValue("@0", userName);
        int count = (int)cmd.ExecuteScalar();
        if (count > 0)
            return Result.Busy;

        // I must admit, also the insert values should be done with SqlParameters.
        cmd = new SqlCommand("INSERT INTO tblUsers (Name, LastName, email, Username, Password) VALUES ('" + name + "', '" + lastName + "', '" + eMail + "', '" + userName + "', '" + password1 + "')", con);
        cmd.ExecuteNonQuery();
        return Result.Completed;
    }
}