C # How to append the data of a able to a table in the database
Method 1:
DataTable table = new DataTable(); //TODO: init table... string connStr = user id= + dbInfo.UserName + ;data source= + dbInfo.DBServerIP + ;persist security info=False;initial catalog= + dbInfo.DatabaseName + ;password= + dbInfo.Password; SqlConnection conn = new SqlConnection(connStr); conn.Open(); SqlBulkCopy sqlBulkCopy = new SqlBulkCopy(conn); sqlBulkCopy.DestinationTableName = dbInfo.TableName; sqlBulkCopy.WriteToServer(table); sqlBulkCopy.Close();
Method 2:
DataTable table = new DataTable(); //TODO: init table... string connStr = user id= + dbInfo.UserName + ;data source= + dbInfo.DBServerIP + ;persist security info=False;initial catalog= + dbInfo.DatabaseName + ;password= + dbInfo.Password; DataTable dt = new DataTable(); SqlConnection conn = new SqlConnection(connStr); SqlCommand cmd = new SqlCommand(string.Format(select * from {0} where 1=2, dbInfo.TableName), conn); SqlDataAdapter sda = new SqlDataAdapter(cmd); SqlCommandBuilder Builder = new SqlCommandBuilder(sda); sda.Fill(dt); DataRow addRow = null; foreach (DataRow row in table.Rows) { addRow = dt.NewRow(); for (int i = 0; i < table.Columns.Count; i++) { addRow[i] = row[i]; } dt.Rows.Add(addRow); } sda.Update(dt);
Summary
1. Only Insert? Use SqlBulkCopy.
2. Insert/Update/Delete? Use DataAdapter. Update.