我的更新查询出了什么问题?

时间:2010-12-06 15:09:17

标签: c# .net-3.5 ado.net

我正在尝试使用.NET的DataAdapter更新一组查询。这是我正在做的简化版本:

       //get all transactions that need to be made
        String sql = "SELECT r.ID, r.[Check], r.Cash, r.Coin, r.TenantID, t.TenantName, r.PropertyID, u.UnitNumber, r.ReceivedFrom, r.isDeposited FROM tblCashReceipts r " +   //I don't actually think all this is needed, if nessecary I can go back and remove unnessecary selections
            "LEFT JOIN tblTenant t " +
            "ON t.ID = r.TenantID " +
            "LEFT JOIN tblProperty p " +
            "ON p.ID = r.PropertyID " +
            "LEFT JOIN tblRentalUnit u " +
            "ON t.UnitID = u.id " +
            "WHERE p.CheckbookID = " + checkbookId;

        //populate the data table
        DataTable receipts = new DataTable();
        using (SqlConnection conn = new SqlConnection(connectionString)) {
            conn.Open();
            SqlDataAdapter adapter = new SqlDataAdapter(sql, conn);
            try {
                adapter.Fill(receipts);
            } catch (Exception ex) {
                MessageBox.Show(ex.Message);
            } finally {
                conn.Close();
            }
        }

        //update the row
        foreach (DataRow row in receipts.Rows) {
            //no longer removing, it will be left entact with the hidden tblCashReceipt row
            row["isDeposited"] = true;
        }

        //now make the database reflect our changes to the tblCashReceiptes
        using (SqlConnection conn = new SqlConnection(connectionString)) {
            SqlDataAdapter receiptsAdapter = new SqlDataAdapter("SELECT ID FROM tblCashReceipts", connectionString);
            //create delete command

            conn.Open();

            SqlCommand receiptsUpdateCommand = new SqlCommand("UPDATE tblCashReceipts SET isDeposited = @isDeposited WHERE ID = @ID", conn);

            SqlParameter idParam = receiptsUpdateCommand.Parameters.Add("@ID", SqlDbType.Int, 5, "ID");
            idParam.SourceVersion = DataRowVersion.Original;

            SqlParameter depositiedParam = receiptsUpdateCommand.Parameters.Add("@isDeposited", SqlDbType.Bit, 1, "isDeposited");
            depositiedParam.SourceVersion = DataRowVersion.Original;

            receiptsAdapter.UpdateCommand = receiptsUpdateCommand;
            receiptsAdapter.Update(receipts);
        }

但是,我发现收据是Adapter.Update(收据);实际上并不会导致数据库更新。我做错了什么?

编写这个的简单方法就是执行:UPDATE tblCashReceipts SET isDeposited = 1 WHERE {my clause}的sql命令但是我想学习如何使用ADO.NET。

1 个答案:

答案 0 :(得分:2)

下面有问题

depositiedParam.SourceVersion = DataRowVersion.Original;

一定是

depositiedParam.SourceVersion = DataRowVersion.Current;