0

问题:插入数据库时​​数据会重复。如何不在数据库中创建重复条目?

我阅读了有关通过不使用

texboxt1.text 

所以我尝试使用

parameters.add()

但是每次插入都会重复条目。

这是数据库的图像...

在此处输入图像描述

这是我的代码

  protected void Button1_Click(object sender, EventArgs e)
    {
        string username = txtuser.Text;
        string firstname = txtfirst.Text;
        string lastname = txtlast.Text;
        string email = txtemail.Text;
        string password = txtpass.Text;
        string gender = rbgender.Text;
        string nationality = ddcountry.Text;

        string Connect_string = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
        SqlConnection Connect = new SqlConnection(Connect_string);

        Connect.Open();

        string pass = FormsAuthentication.HashPasswordForStoringInConfigFile(password, "MD5");
        SqlCommand Command = new SqlCommand("INSERT INTO [Users] (username, firstname, lastname, email, password, gender, nationality) VALUES (@username, @firstname, @lastname, @email, @password, @gender, @nationality)", Connect);
        Command.Parameters.AddWithValue("@username", username);
        Command.Parameters.AddWithValue("@firstname", firstname);
        Command.Parameters.AddWithValue("@lastname", lastname);
        Command.Parameters.AddWithValue("@email", email);
        Command.Parameters.AddWithValue("@password", pass);
        Command.Parameters.AddWithValue("@gender", gender);
        Command.Parameters.AddWithValue("@nationality", nationality); 
        Command.ExecuteNonQuery();


        int success = Command.ExecuteNonQuery();

        if (success > 0)
        {
            Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
            Label1.Visible = true;
            Label1.Text = "You have successfully registered";
            Connect.Close();
        }
        else
        {
            Label1.Text = "Your information has not been entered to database";
            Connect.Close();
        }

当我使用 INSERT INTO Table () VALUE '"+textbox1.text +"' 它不会被重复,但是是的,SQL 注入的东西。

4

2 回答 2

5

您有两次调用 ExecuteNonQuery 实际触发命令:

    Command.Parameters.AddWithValue("@nationality", nationality); 
    Command.ExecuteNonQuery(); //CALLED HERE First Time

    int success = Command.ExecuteNonQuery(); //CALLED HERE Second Time (This is the one you want)

    if (success > 0)
    {
        Label1.ForeColor = System.Drawing.ColorTranslator.FromHtml("#12223");
        Label1.Visible = true;
        Label1.Text = "You have successfully registered";
        Connect.Close();
    }
于 2013-06-27T02:39:47.627 回答
2

您通过这些行执行了两次查询:

Command.ExecuteNonQuery();

int success = Command.ExecuteNonQuery();

删除第一个Command.ExecuteNonQuery()并将第二个保留为int success.

于 2013-06-27T02:39:35.690 回答