How to append data from a DataTable into a table in a database in C #

Source: Internet
Author: User

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 #

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.