DataTable obtains the column name DataTable and updates it to the database in batches. datatable column names
I haven't written anything for a long time. I haven't worked hard on technology in the past few months. Let's talk about the usage of the recently learned DataTable, which is suitable for beginners.
1 DataTable get column name
When processing data, everyone will use the model. When traversing data from the datatable, you can use the columns attribute of the datatable to get the column name, and then you can dynamically use the datatable
It is convenient to generate a josn string and then convert the json string into the desired model ?.
The following describes how to convert a able to a json array.
Private string DataTableToModel (DataTable dt) {var jsonStr = ""; if (dt. rows. count> 0) {jsonStr = "["; foreach (DataRow row in dt. rows) {jsonStr + = "{"; foreach (DataColumn item in dt. columns) {var type = item. dataType; // You can also obtain the column data type if (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 (',') + "]";} return jsonStr ;}
In this way, you do not need to manually specify the column name every time, and this method is also very universal. You can call this method for all the places where data is read from the datatable.
Use DataTable to update data in batches
Because datatable batch update is used for Excel import, this method is undoubtedly the fastest and most convenient.
SqlBulkCopy bcp = new SqlBulkCopy (connectionString, SqlBulkCopyOptions. useInternalTransaction); sqlbulkcopy. destinationTableName = "Table_1"; // The table name bcp in the database. columnMappings ("ColumnName", "TargetColumnName"); // if all the corresponding columns in the current data and the target table correspond to each other, you do not need to set this attribute sqlbulkcopy. writeToServer (dataset. tables [0]);
OK. I 'd like to share so much with you. If you have any shortcomings, I hope you will not be able to give me any further advice.
How to retrieve the column name in the DataTable
DataTable dt;
Foreach (DataColumn dc in dt. Columns)
{
Response. Write (string. Format ("column name: {0}, data type: {1}", dc. ColumnName, dc. DataType ));
}
How to Use the ableableselect method to retrieve two data columns: "PPI" and "TEM" and put the data in the new DataTable
DataRow [] foundRows = oldDataTable. select (" = 'ppi 'and = 'tem '");