Method One :
DataTable table = new DataTable (); Todo:init Table ... String connstr = "User id=" + dbinfo.username + ";d ata source=" + Dbinfo.dbserverip + ";p ersist security Info=false;initia L catalog= "+ dbinfo.databasename +";p assword= "+ Dbinfo.password; SqlConnection conn = new SqlConnection (CONNSTR); Conn. Open (); SqlBulkCopy SqlBulkCopy = new SqlBulkCopy (conn); Sqlbulkcopy.destinationtablename = Dbinfo.tablename; Sqlbulkcopy.writetoserver (table); Sqlbulkcopy.close ();
Method Two:
DataTable table = new DataTable (); Todo:init Table ... string connstr = "User id=" + dbinfo.username + ";d ata source=" + Dbinfo.dbserverip + ";p Ersist Security info=false;initial catalog= "+ dbinfo.databasename +";p assword= "+ 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);
Summarize
1. Only Insert? So use SqlBulkCopy.
2. Insert/update/delete? So use DataAdapter.Update.
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
How to append data from a DataTable into a table in a database in C #