代码插入到数据库中的两行
问题描述:
当该表单打开时,该表单已经有一个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;
}
}
答
因为你两次执行查询:
myCommand.ExecuteNonQuery();
Int32 newId = (Int32)myCommand.ExecuteScalar();
只需执行一次:
Int32 newId = (Int32)myCommand.ExecuteScalar();
答
您正在使用myCommand.ExecuteNonQuery();
两次。所以它插入重复的项目。使用一次。