2
我想用.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);
}
然而,我發現,receiptsAdapter.Update(收據);實際上並沒有導致數據庫被更新。我究竟做錯了什麼?
編寫這個的簡化方法只是執行sql的命令:UPDATE tblCashReceipts SET isDeposited = 1 WHERE {my clause}
但我想學習如何使用ADO.NET的東西。