我遇到了未保存到SQL Server數據庫的更改。使用SqlDataAdapter不保存到數據庫的更改
我可以正確讀取數據庫,當調用RefreshGrid()
刷新數據庫時,gridview會正確更新。但是,當重新啓動程序或檢查實際數據庫時,不會發生變化。
我通常會爲此使用實體框架,但有時候需要學習其他方法。
private string conString = ConfigurationManager.ConnectionStrings["RewardsConnectionString"].ConnectionString;
private RewardsDS rewardsDset = new RewardsDS();
private SqlDataAdapter CreateDataAdapter(SqlConnection conn)
{
// Build the selection query.
SqlDataAdapter rewardsAdapter = new SqlDataAdapter();
SqlCommand selectCommand = new SqlCommand("SELECT * FROM Purchases", conn);
rewardsAdapter.SelectCommand = selectCommand;
// Build the insertion query
SqlCommand insertCommand = new SqlCommand(
@"INSERT INTO Purchases (PurchaseDate, Amount, CustomerId)
VALUES (@PurchaseDate, @Amount, @CustomerId)", conn);
insertCommand.Parameters.Add("@PurchaseDate", SqlDbType.DateTime, 0, "PurchaseDate"); // Not sure about this zero ...
insertCommand.Parameters.Add("@Amount", SqlDbType.Decimal, 0, "Amount");
insertCommand.Parameters.Add("@CustomerId", SqlDbType.Int, 0, "CustomerId");
rewardsAdapter.InsertCommand = insertCommand;
// Build the update query
SqlCommand updateCommand = new SqlCommand(
@"UPDATE Purchases SET Amount = @Amount, PurchaseDate = @PurchaseDate WHERE PurchaseId = @PurchaseId", conn);
updateCommand.Parameters.Add("@Amount", SqlDbType.Decimal, 0, "Amount");
updateCommand.Parameters.Add("@PurchaseDate", SqlDbType.DateTime, 0, "PurchaseDate");
SqlParameter param = updateCommand.Parameters.Add("@PurchaseId", SqlDbType.Int, 0, "PurchaseId");
param.SourceVersion = DataRowVersion.Original;
rewardsAdapter.UpdateCommand = updateCommand;
// Build the delete query
SqlCommand deleteCommand = new SqlCommand(
"DELETE FROM Purchases WHERE PurchaseId = @PurchaseId", conn);
param = deleteCommand.Parameters.Add("@Id", SqlDbType.Int, 0, "PurchaseId");
param.SourceVersion = DataRowVersion.Original;
rewardsAdapter.DeleteCommand = deleteCommand;
return rewardsAdapter;
}
// Gets changes and saves them to the database.
private void SaveChanges()
{
using (SqlConnection conn = new SqlConnection(conString))
{
var fadapter = CreateDataAdapter(conn);
conn.Open();
DataSet changes = rewardsDset.GetChanges();
try
{
fadapter.Update(changes, "Purchases");
}
catch (Exception ex)
{
MessageBox.Show("There are no updates to be saved");
}
conn.Close();
rewardsDset.AcceptChanges();
}
}
// Refresh the dataGridView from the database
private void RefreshGrid()
{
rewardsDset.Clear();
using (SqlConnection conn = new SqlConnection(conString))
{
conn.Open();
SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT * FROM Purchases", conn);
myAdapter.Fill(rewardsDset, "Purchases");
conn.Close();
dataGridView1.DataSource = null;
this.dataGridView1.DataSource = rewardsDset.Tables["Purchases"];
}
}
感謝您的快速回答!正如我暗示的,被實體框架寵壞了,我在這裏毫無頭緒。但我確實相信這是從DataSet執行的。在RewardsDS中,我有以下生成的行: 'int returnValue = this.Adapter.InsertCommand.ExecuteNonQuery();' 我是否需要在另一個地方調用它? – mrapan 2014-11-25 14:41:30