Problem With Updating Database through DataAdapters/datasets in C#/Visual studio
I try updating my database after updating the dataset, but evenafter calling the data adapter's update function the underlying database doesn't change. I used SqlCommandBuilder and it still wouldn't update. Once I have the GUI open I can submit and search for values in my dataset but once I close it then re run it, all the changes are gone. Help?
Code:
//in my form load event
con = new System.Data.SqlClient.SqlConnection();
ds1 = new DataSet();
ds2 = new DataSet();
con.ConnectionString = "Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;Integrated Security=True;User Instance=True";
con.Open();
MessageBox.Show("Database Open.");
string sql = "SELECT * From tblPurchases";
da = new System.Data.SqlClient.SqlDataAdapter(sql, con);
string cust = "SELECT * From tblCustomers";
da2 = new System.Data.SqlClient.SqlDataAdapter(cust, con);
da.Fill(ds1, "Purchases");
numOf开发者_StackOverflow中文版Records = ds1.Tables["Purchases"].Rows.Count;
da2.Fill(ds2, "Customers");
numOfCustomers = ds2.Tables["Customers"].Rows.Count;
con.Close();
MessageBox.Show("Database Closed.");
Code:
//in my submit button click event
System.Data.SqlClient.SqlCommandBuilder cb;
cb = new System.Data.SqlClient.SqlCommandBuilder(da);
System.Data.SqlClient.SqlCommandBuilder cb2;
cb2 = new System.Data.SqlClient.SqlCommandBuilder(da2);
DataRow dRow = ds1.Tables["Purchases"].NewRow();
DataRow dRow2 = ds2.Tables["Customers"].NewRow();
//dRow updating happens here
ds1.Tables["Purchases"].Rows.Add(dRow);
ds2.Tables["Customers"].Rows.Add(dRow2);
da.Update(ds1, "Purchases");
da2.Update(ds2, "Customers");
That's it. There are no error messages, it's just that even with that, the underlying database doesn't update and the updates only go as far as the dataset.
The SqlDataAdapter.Update()
method returns an integer with the number of rows successfully updated. Consider loading that value into a variable to determine if any rows were reported as updated.
The SqlCommandBuilder likely needs its .GetUpdateCommand()
method called. GetUpdateCommand
gets the automatically generated SqlCommand object required to perform updates on the database.
cb.GetUpdateCommand();
cb2.GetUpdateCommand();
da.Update(ds1, "Purchases");
da2.Update(ds2, "Customers");
Consider running SQL Server Profiler against your server to determine the TSQL statements that are being generated by the SqlCommand. This will be extremely helpful in determining if the database and statements are as you expect.
All that you need to do is to change the
con.ConnectionString =
`"Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\Database1.mdf;
Integrated Security=True;User Instance=True";
that is going to be generated at run time to the real one, like changing |DataDirectory|
to the real path. Example: c:\\blablablabla
.
精彩评论