【问题标题】:Code is inserting two Rows into database代码将两行插入数据库
【发布时间】:2017-08-13 11:46:22
【问题描述】:

我正在制作一个表单,当该表单打开时,该表单中已经有一个 ID 显示。而且我只是以打开的形式更新它的列。但我的代码是在数据库中插入两个 ID。

这是我的代码。

 private void btnAdd_Click(object sender, EventArgs e)
    {
        string insertSql =
       "INSERT INTO Products(BrandName) OUTPUT INSERTED.ProductID VALUES(NULL)";

        using (SqlConnection myConnection = new SqlConnection("Data Source=BENJOPC\\SQLEXPRESS;Initial Catalog=MARISCHELLdatabase;Integrated Security=True"))
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand(insertSql, myConnection);

            myCommand.ExecuteNonQuery();

            Int32 newId = (Int32)myCommand.ExecuteScalar();
            string aydi = newId.ToString();

            myConnection.Close();

            AddProducts ap = new AddProducts(aydi);
            ap.FormClosing += new FormClosingEventHandler(this.AddProducts_FormClosing);
            ap.ShowDialog();
            pictureBox1.Image = null;
        }

    }

【问题讨论】:

    标签: c# sql winforms


    【解决方案1】:

    因为您要执行两次查询:

    myCommand.ExecuteNonQuery();
    
    Int32 newId = (Int32)myCommand.ExecuteScalar();
    

    只需执行一次:

    Int32 newId = (Int32)myCommand.ExecuteScalar();
    

    【讨论】:

      【解决方案2】:

      您使用了两次myCommand.ExecuteNonQuery();。所以它正在插入重复的项目。使用一次。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2011-04-16
        • 2016-03-22
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-15
        • 1970-01-01
        相关资源
        最近更新 更多