我的代码中重复键的异常

时间:2014-06-12 20:38:28

标签: c# sql-server database datagridview textbox

我有一个Form,其中包含一个“Add”按钮和一个textBox,用于向数据库表添加信息。

在插入之前,我需要检查在TextBox中输入的代码是否可用。

我的问题是我收到错误,因为它试图添加“重复的主键”而我不确定错误的来源。

以下是我目前的代码:

private void button2_Click(object sender, EventArgs e)
{
    SqlConnection connection1 = new SqlConnection(connectionString);
    connection1.Open();

    String reqt1="select numero_cpte from compte where numero_cpte="+textBox1.Text+";";

    SqlCommand sql1 = new SqlCommand(reqt1, connection1);

    int d = int.Parse(textBox1.Text);
    int dd = Convert.ToInt32(sql1.ExecuteScalar());

    if(d == dd) 
    { 
        int o1 = sql1.ExecuteNonQuery();
        MessageBox.Show("this account is not valide!!","Fiche ");
        connection1.Close();
    }

    if (String.IsNullOrEmpty(textBox1.Text) == true)
    {
        MessageBox.Show("You should insert the code!!","Fiche", 
                         MessageBoxButtons.OK,MessageBoxIcon.Information);
    }
    else 
    {
        SqlConnection connection = new SqlConnection(connectionString);
        connection.Open();
        SqlCommand sql = new 
                 SqlCommand("insert into compte values(" + textBox1.Text + ",'" +
                 textBox2.Text + "','" + type_cpteComboBox.SelectedItem.ToString() + 
                 "','" + textBox2.Text + "','" + comboBox1.SelectedItem.ToString() +
                 "'," + comboBox2.SelectedItem.ToString() + ",'" + 
                 checkBox1.Checked.ToString() + "','" + checkBox2.Checked.ToString() + 
                 "','" +textBox5.Text+ "','" +textBox6.Text+ "');", connection);

        int o = sql.ExecuteNonQuery();

        MessageBox.Show(o + "Success of add","Fiche");

        connection.Close();

        textBox1.Text = "";
        textBox2.Text = "";
    }

这是我看到的错误: enter image description here

insert命令工作正常,但是当我尝试测试我要在基础中添加的代码是否存在时(通过键入我知道的代码存在),我得到了这个异常。

2 个答案:

答案 0 :(得分:2)

即使您发现您的号码是重复的,您的代码也会显示为添加代码。尝试添加“返回”;关闭连接后。

MessageBox.Show(“Ce compte existe.Veuillez sasirunnumérodecompte valide !!”,“Fiche Comptes”); connection1.Close();
返回;

答案 1 :(得分:1)

    private object ExecuteScalar(string sql)
    {
        using (SqlConnection connection1 = new SqlConnection(connectionString))
        {
            connection1.Open();
            SqlCommand sql1 = new SqlCommand(sql, connection1);
            return sql1.ExecuteScalar();
        }
    }  

这样做的好处是,您始终知道在完成后您的连接将被关闭。即使您只打算一次调用此方法,它也会提高可读性,因此非常有用。