保存数据集数据库 [英] Saving Dataset to database
问题描述
我想一个数据保存到数据库中。我从另一个类的数据集,现在更改将在表单上由用户在一个DataGridView做,然后更改数据集需要被保存在数据库中。
I am trying to save a dataset to a database. I got a dataset from another class, Now changes will be made on the form by a user on a datagridview, then the changed Dataset needs to be saved in the database.
我使用下面的代码;它不产生任何错误,但数据不被保存在数据库中。
I am using the below code; Its not generating any errors, but the data is not being saved in the database.
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;
}
}
我在做什么错在这里?有在网络上的方式来保存数据集,如果datset创建,编辑和保存在同一类等,但我想有在mySqlService类中选择数据的方法。 ?我应该如何,现在可以保存数据到数据库中。
What am I doing wrong here? There are ways on the web to save the dataset, if the datset is created, edited and saved in the same class etc., BUT I would like to have the select dataset method in the mySqlService class. How should I, now can save the dataset to the database?
编辑:
我还评论说,被要求使代码工作的三条线。代码工作了。
I have commented the three lines that were required to make the code work. The code works now.
推荐答案
为了运行的更新的的方法SqlDataAdapter的
您必须配置的InsertCommand
,的DeleteCommand
和更新命令
以及的SelectCommand
的SqlDataAdapter或构造的 SqlCommandBuilder 对象,它含蓄地配置这些命令。
In order to run Update method of SqlDataAdapter
you must have to configure InsertCommand
, DeleteCommand
and UpdateCommand
properties along with SelectCommand
of SqlDataAdapter or construct the SqlCommandBuilder object which configure these commands implicitly.
这篇关于保存数据集数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!