用户注册表单使多个记录访问数据库

问题描述 投票:0回答:1

command.CommandText = "insert into Tunnukset (Käyttäjänimi,Salasana) values('" + txtkäyttäjä.Text + "','" + txtsal.Text + "')";
command.ExecuteNonQuery();                                      //command.CommandText = "insert into Tunnukset (Käyttäjänimi,Salasana) values('" + txtkäyttäjä.Text + "','" + txtsal.Text +  "')";
OleDbDataReader reader = command.ExecuteReader();
int count = 1;
while (reader.Read())
{
    count++;
}
if (txtkäyttäjä.Text == "")
{
    MessageBox.Show("Käyttäjänimi kentt� tyhj�");//username field empty
    this.Hide();
    Form6 frm6 = new Form6();
    frm6.ShowDialog();
}
if (txtsal.Text == "")
{
    MessageBox.Show("Salasana kentt� tyhj�");//passoword field empty
    this.Hide();
    Form6 frm6 = new Form6();
    frm6.ShowDialog();
}
else if (count > 1)
{
    MessageBox.Show("Käyttäjänimi varattu");//username taken
    this.Hide();
    Form6 frm6 = new Form6();
    frm6.ShowDialog();
}

if (txtsal.Text != txtvarmista.Text)
{
    MessageBox.Show("salasana ei t�sm��");//password do not match
}
else if (count == 1)
{
    MessageBox.Show("Tunnusten luominen onnistui");//Signup successfull

    con.Close();
    this.Hide();
    Form5 f5 = new Form5();
    f5.ShowDialog();
c# database access
1个回答
0
投票

按照@Steve的说法回答

你的INSERT声明执行两次:

command.ExecuteNonQuery();
OleDbDataReader reader = command.ExecuteReader();

您应该根据您想要执行的操作删除其中一个调用。


您应该考虑的其他内容

  1. 您的代码容易受到SQL注入攻击: command.CommandText = "insert into Tunnukset (Käyttäjänimi,Salasana) values('" + txtkäyttäjä.Text + "','" + txtsal.Text + "')"; 您应该考虑使用参数化查询来摆脱此漏洞。
  2. 执行查询后,检查用户名和密码是否为空。 考虑在查询部分之前移动这些块: if (txtkäyttäjä.Text == "") if (txtsal.Text == "")
  3. 如果要检查名称是否已被占用,则应该有SELECT查询。 else if (count > 1) { MessageBox.Show("Käyttäjänimi varattu");//username taken this.Hide(); Form6 frm6 = new Form6(); frm6.ShowDialog(); } 您告诉用户在插入用户名后已经使用了他的用户名,所以已经太晚了。

伪代码尝试

if(string.IsNullOrEmpty(username))
{
    // tell username is empty
}
else if(string.IsNullOrEmpty(password))
{
    // tell password is empty
}
else if(password != passwordConfirmation)
{
    // tell passwords do not match
}
else if(UserAlreadyExists(username))
{
    // tell username is taken
}
else
{
    if(InsertUser(username, password))
    {
        // tell sign-in successfull
    }
}

private bool UserAlreadyExists(string username)
{
    // use SELECT parameterized query
    // return user existance (true or false)
}

private bool InsertUser(string username, string password)
{
    // use INSERT parameterized query
    // return success (true or false)
}
© www.soinside.com 2019 - 2024. All rights reserved.