我正在嘗試將數據集保存到數據庫。我從另一個類獲得了一個數據集,現在用戶在datagridview上對錶單進行更改,然後將更改後的數據集保存到數據庫中。將數據集保存到數據庫
我正在使用下面的代碼;它不會產生任何錯誤,但數據不會被保存在數據庫中。
public class myForm
{
DataSet myDataSet = new DataSet();
public void PouplateGridView()
{
try
{
SqlService sql = new SqlService(connectionString); // Valid Connection String, No Errors
myDataSet = sql.ExecuteSqlDataSet("SELECT * FROM Qualification"); // Returns a DataSet
myDataGridView.DataSource = myDataSet.Tables[0];
myDataGridView.AutoGenerateColumns = true;
myDataGridView.AutoResizeColumns();
}
catch (Exception ex)
{
MessageBox.Show(ex.InnerException + Environment.NewLine + ex.Message, "Error");
this.Close();
}
}
private void btnSave_Click(object sender, EventArgs e)
{
//myDataSet.AcceptChanges();EDIT:Don't know why, but this line wasn't letting the chane in db happen.
SqlCommand sc = new SqlCommand("SELECT * FROM Qualification", sql.Connection); //ADDED after Replies
SqlDataAdapter da = new SqlDataAdapter();
SqlCommandBuilder scb = new SqlCommandBuilder(da); //ADDED after replies
da.Update(myDataSet.Tables[0]);
}
}
public class mySqlService
{
public DataSet ExecuteSqlDataSet(string sql)
{
SqlCommand cmd = new SqlCommand();
this.Connect();
SqlDataAdapter da = new SqlDataAdapter();
DataSet ds = new DataSet();
cmd.CommandTimeout = this.CommandTimeout;
cmd.Connection = _connection;
if (_transaction != null) cmd.Transaction = _transaction;
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
da.SelectCommand = cmd;
da.Fill(ds);
da.Dispose();
cmd.Dispose();
if (this.AutoCloseConnection) this.Disconnect();
return ds;
}
}
我在做什麼錯在這裏?如果數據集被創建,編輯並保存在同一個類中,網絡上有很多方法可以保存數據集,但是我希望在mySqlService類中有選擇數據集方法。我現在應該如何將數據集保存到數據庫?
編輯: 我已經評論了使代碼工作所需的三條線。代碼現在可用。
謝謝,它工作:) – 2012-07-24 07:11:10