在 SQL C# 中插入的双精度数据



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

数据库中双条目的示例图像。

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);
                }
            }

你给ExecuteNonQuery()打了两次电话。

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

查询两次。改变:

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

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

最新更新