我正在制作一个表单,当该表单打开时,该表单中已经有一个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;
}
}
Run Code Online (Sandbox Code Playgroud)
因为您执行了两次查询:
myCommand.ExecuteNonQuery();
Int32 newId = (Int32)myCommand.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
只需执行一次:
Int32 newId = (Int32)myCommand.ExecuteScalar();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
53 次 |
| 最近记录: |