The business needs to copy data from one database to another. Of course, you can copy data one by one, but the two databases have the same table structure. It is better to operate DataSet to copy data to another database in batches, regardless of development efficiency or execution efficiency. Note: 1. The database must have a primary key.
The business needs to copy data from one database to another. Of course, you can copy data one by one, but the two databases have the same table structure. It is better to operate DataSet to copy data to another database in batches, regardless of development efficiency or execution efficiency. Note: 1. The database must have a primary key.
The business needs to copy data from one database to another. Of course, you can copy data one by one, but the two databases have the same table structure. It is better to operate DataSet to copy data to another database in batches, regardless of development efficiency or execution efficiency.
Note the following:
1. The database must have a primary key to facilitate addition, deletion, modification, and query;
2. SqlDataAdapter must be placed in SqlCommandBuilder to perform modifications in DataSet in batches;
3. The modified DataSet can be updated only after the AcceptChanges () method is executed;
4. The database where SqlDataAdapter performs Update is not necessarily a Fill database, as long as the table structure is the same.
The sample code is as follows:
public void CopyData(DataSet ds, string conString, string sql, string tableName) { SqlConnection conn = new SqlConnection(conString); try { conn.Open(); SqlDataAdapter ada = new SqlDataAdapter(sql, conn); SqlCommandBuilder cb = new SqlCommandBuilder(ada); DataSet destDataSet = new DataSet(); ada.Fill(destDataSet, tableName); //Delete Rows foreach (DataRow item in destDataSet.Tables["Pattern"].Rows) { item.Delete(); } DataTable dt = null; dt = destDataSet.Tables["Pattern"].GetChanges(); if (dt != null) { ada.Update(dt); } //Insert Rows foreach (DataRow item in ds.Tables["Pattern"].Rows) { item.SetAdded(); } dt = ds.Tables["Pattern"].GetChanges(); if (dt != null) { ada.Update(dt); } } catch (Exception ex) { throw ex; } finally { conn.Close(); } }
This is a database replication method. The function is to delete the data in the original database, and then update the data in the DataSet to the database based on the passed DataSet.
This is just a small example. I hope you can correct it.