从两个表中删除?

时间:2015-10-26 12:51:34

标签: c# sql sql-server

我正在尝试删除两个不同表中的两个项目,但它无效。

我的代码:

protected void btnRemove(object sender, EventArgs e)
{
    conn.Open();
    SqlCommand cmd = new SqlCommand("delete from Car where CarID=" + lstCar.SelectedValue, conn);
    SqlCommand cmd1 = new SqlCommand("delete from Orders where OrderID=" + lstOrders.SelectedValue, conn);
    cmd.ExecuteNonQueryAsync();
    cmd1.ExecuteNonQueryAsync();
    conn.Close();
}

3 个答案:

答案 0 :(得分:2)

使用参数并且不要将值连接到SQL中,尝试类似.....

protected void btnRemove(object sender, EventArgs e)
{
    conn.Open();

    SqlCommand cmd = new SqlCommand("delete from Car where CarID= @CarID", conn);
    cmd.Parameters.AddWithValue("@CarID", lstCar.SelectedValue);

    SqlCommand cmd1 = new SqlCommand("delete from Orders where OrderID= @OrderID" , conn);
    cmd1.Parameters.AddWithValue("@OrderID", lstOrders.SelectedValue);

    cmd.ExecuteNonQuery();
    cmd1.ExecuteNonQuery();

    conn.Close();
}

答案 1 :(得分:1)

像这样的东西

protected void btnRemove(object sender, EventArgs e) {
  // Do not use external connection, create your own instead 
  // Put IDisposable into using
  using (SqlConnection c = new SqlConnection(YourConnectionString)) {
    c.Open();

    // Make SQL Readable  
    String sql =
      @"delete 
          from Car
         where CarID = @prm_CarId; -- Note ';'

        delete 
          from Orders 
         where OrderID = @prm_OrderId";  

    // Put IDisposable into using
    using (SqlCommand cmd = new SqlCommand(sql, c)) {
      // use parameters
      cmd.Parameters.AddWithValue("@prm_CarId", lstCar.SelectedValue); 
      cmd.Parameters.AddWithValue("@prm_OrderId", lstOrders.SelectedValue);    

      // Your error:
      // No "Async"!: wait for query completion and only then close the connection
      // ... or use await 
      cmd.ExecuteNonQuery(); 
    }
  }
}

答案 2 :(得分:0)

我修好了。

conn.Open();
            string sql1 = "delete from Orders where OrderID='" + lstOrders.SelectedValue + "'";
            SqlCommand cmd1 = new SqlCommand(sql1, conn);
            cmd1.ExecuteNonQuery();
            string sql = "Delete from Car where CarID='" + lstCar.SelectedValue + "'";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.ExecuteNonQuery();
            conn.Close();