代码将两行插入数据库

时间:2017-08-13 11:46:23

标签: c# sql winforms

我正在制作一个表单,当该表单打开时,该表单中已经有一个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;
        }

    }

enter image description here

2 个答案:

答案 0 :(得分:5)

因为您要执行两次查询:

myCommand.ExecuteNonQuery();

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

只需执行一次:

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

答案 1 :(得分:0)

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

相关问题