在sql中插入的双重数据c#

时间:2018-03-16 07:05:50

标签: c# sql

这只是注册新帐户凭据的简单方法。我的问题是每当我点击保存按钮时,数据将在数据库中保存两次。

Sample image of the double entry in the database.

using (SqlConnection con = new SqlConnection(conString))
            {
                try
                {
                    string query = ("INSERT INTO Tbl_Staff (Name,pos,username,password) VALUES (@name,@pos,@username,@password)");

                    using (SqlCommand cmd = new SqlCommand(query, con))
                    {
                        cmd.Parameters.AddWithValue("@name", textBox1.Text);
                        cmd.Parameters.AddWithValue("@pos", textBox4.Text);
                        cmd.Parameters.AddWithValue("@username", textBox2.Text);
                        cmd.Parameters.AddWithValue("@password", textBox3.Text);
                        con.Open();
                        cmd.ExecuteNonQuery();
                        int result = cmd.ExecuteNonQuery();

                        //MessageBox.Show(result.ToString());

                        // Check Error
                        if (result > 0)
                            MessageBox.Show("Credentials has been successfully added.","" ,MessageBoxButtons.OK, MessageBoxIcon.Information);

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

                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                }
            }

2 个答案:

答案 0 :(得分:1)

您正在拨打ExecuteNonQuery()两次。

cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();

答案 1 :(得分:1)

您将查询执行两次。 改变:

con.Open();
cmd.ExecuteNonQuery();
int result = cmd.ExecuteNonQuery();

con.Open();
int result = cmd.ExecuteNonQuery();