DataTable Fetch Column name DataTable batch update to database

Source: Internet
Author: User

Long time no write things, these months also did not work hard to study technology, guilt AH. Next, just learn the usage of the DataTable recently, novice suitable to look.

1 DataTable Get Column name

In the process of data processing, everyone will use the model, when traversing the data from the DataTable can use the DataTable Columns property to get the column name, and then you can dynamically use the DataTable

Is it convenient to generate a josn string and then convert the JSON string into the model you want?

Here's how to convert a DataTable to a JSON array.

Private string Datatabletomodel (DataTable DT)        {   
var jsonstr= "";
       if(dt. Rows.Count >0)
{
Jsonstr= "["foreach(DataRow rowinchdt. Rows) {
jsonstr+= "}";
              foreach(DataColumn Iteminchdt. Columns) {varType=item. Datatype;//can also get the data type of the columnif(item. Datatype.equals (System.Type.GetType ("System.DateTime")) {convert.todatetime (Row[item). ToString ()]). ToString ("YYYY-MM-DD HH:mm:ss"). Trim ()); }
Else
{
jsonstr+= "\ "" +item. ToString () + "\": \ "" +Row[item. ToString ()]. ToString () + "\", "
}
              }
jsonstr+= "},";
}
Jsonstr=jsonstr.trimend (', ') + "]"; } jsonstr;
}

This way you do not have to manually specify the column name each time, and this method is very versatile, and all of the data from the DataTable can be called this method.

Batch update data using DataTable

Because to do Excel import, using the DataTable batch update, this method is undoubtedly the fastest and most convenient.

New"table_1"; // table names in the database bcp. ColumnMappings ("ColumnName","targetcolumnname"  )///The corresponding column between the current data and the target table can be used without setting this property sqlbulkcopy if all corresponds. WriteToServer (DataSet. tables[0]);

OK, first share so much, if there are shortcomings also hope you can advise.

DataTable Fetch Column name DataTable batch update to database

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.