任何人都可以解释为什么我仍然可以输入这些数据的副本?

时间:2014-02-14 16:38:58

标签: c# asp.net .net sql-server-2012 visual-studio-2013

我试图阻止两条记录被复制到我的数据库中,但即使我已经输入了代码,它仍然会发生任何帮助,我们将不胜感激!

这是我的代码:

 if (Page.IsPostBack == true)
 {
             SqlConnection conn = new SqlConnection("Data Source=TOSHIBA0007\\TESTSERVER;Initial Catalog=users;Integrated Security=True");
             conn.Open();
             string checkcompany = "select count(*) from Company where CompanyName = @CompanyName";
             SqlCommand cc = new SqlCommand(checkcompany, conn);
             cc.Parameters.AddWithValue("@CompanyName", InputCompany.Text);
             int temp = Convert.ToInt32(cc.ExecuteScalar().ToString());
             conn.Close();

             if (temp == 1)
             {
                 Response.Write("Company is already registered! if this is incorrect please email us at info@getmeanapprentice.com");
             }
         }
}

修改

protected void Button1_Click(object sender, EventArgs e)
{
        Guid newGUID = Guid.NewGuid();

        SqlConnection Comp = new SqlConnection("Data Source=TOSHIBA0007\\TESTSERVER;Initial Catalog=users;Integrated Security=True");
        {
            SqlCommand xp = new SqlCommand("insert into Company(GUID, CompanyName, Password, AddressLine1, AddressLine2, AddressLine3, City, PostCode, County, Country, Email, Telephonenumber, Faxnumber)Values(@ID, @CompanyName, @Password, @AddressLine1, @AddressLine2, @AddressLine3, @City, @PostCode, @County, @Country, @Email, @TelephoneNumber, @Faxnumber)",Comp);
            xp.Parameters.AddWithValue("@ID", newGUID.ToString());
            xp.Parameters.AddWithValue("@CompanyName", InputCompany.Text);
            xp.Parameters.AddWithValue("@Password", InputPassword.Text);
            xp.Parameters.AddWithValue("@AddressLine1", InputAddress1.Text);
            xp.Parameters.AddWithValue("@AddressLine2", InputAddress2.Text);
            xp.Parameters.AddWithValue("@AddressLine3", InputAddress3.Text);
            xp.Parameters.AddWithValue("@City", InputCity.Text);
            xp.Parameters.AddWithValue("@PostCode", InputPostcode.Text);
            xp.Parameters.AddWithValue("@County", InputCounty.Text);
            xp.Parameters.AddWithValue("@Country", InputCountry.Text);
            xp.Parameters.AddWithValue("@Email", InputEmail.Text);
            xp.Parameters.AddWithValue("@TelephoneNumber", InputTelephone.Text);
            xp.Parameters.AddWithValue("@Faxnumber", InputFax.Text);

            Comp.Open();
            xp.ExecuteNonQuery();
            Comp.Close();

            if (IsPostBack)
            {
                Response.Redirect("Registration.aspx");
            }
        }
    }

2 个答案:

答案 0 :(得分:1)

如果您有多个同名公司,那么这一行

if (temp == 1)

将失败,因为temp将为2或更多。

替换此行
if (temp >= 1)

还要考虑在CompanyName列上添加唯一约束,因为这在您的方案中至关重要。

答案 1 :(得分:0)

我没有看到您的测试和按钮点击之间的链接。您在页面加载中进行测试,如果已有此ID的公司,则向页面发出警告。这不会停止按钮点击代码的运行。

您需要在按钮单击中检查公司,如果存在,请不要运行该代码。