如何将数据从数据表保存到数据库 [英] How to Save data from datatable to database

查看:183
本文介绍了如何将数据从数据表保存到数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

DataSet ds = new DataSet();
DataTable dt = new DataTable();
dt.TableName = "MyTable";
foreach (DataGridViewColumn col in dataGridView1.Columns)
{
    dt.Columns.Add(col.DataPropertyName, col.ValueType);
}
foreach (DataGridViewRow gridRow in dataGridView1.Rows)
{
    if (gridRow.IsNewRow)
        continue;
    DataRow dtRow = dt.NewRow();
    for (int i1 = 0; i1 < dataGridView1.Columns.Count; i1++)
        dtRow[i1] = (gridRow.Cells[i1].Value == null ? DBNull.Value : gridRow.Cells[i1].Value);
    dt.Rows.Add(dtRow);
}
ds.Tables.Add(dt);
System.Diagnostics.Debugger.Break();



这是我的代码,我需要将数据表插入MyTable,并且列将是动态的,但我无法一直创建列。

请问任何人都可以告诉我该怎么做?


This is my code and I need to insert the datatable into "MyTable" and the Columns will be dynamic,but I cant be creating columns all the time.
Please can any one tell me how to do this?

推荐答案

对于任何给定的要求,您需要指定列定义。这将映射到数据库中的相应表。另外,如何指定数据表中哪个列的值映射到物理表中的哪一列?



理想情况下,映射应该是基于确切名称的1:1。就像datatable的名称对应物理表的名称和物理表中相同列之后命名的数据表中的每一列。



您可以迭代数据源并创建列通过索引,但是你必须确保插入查询以与插入数据表中相同的顺序获取列。



网格的AutoGenerateColumns属性仅以这种方式,但顺序相反
For any given requirement, you will need to specify the column definition. This will map to the corresponding table in the database. Else how will you specify which column's value in the datatable maps to which column in the physical table?

Ideally the mapping should be 1:1 based on exact names. Like the name of datatable corresponds to the name of physical table and each column in datatable named after same column in physical table.

You can iterate over your datasource and create columns by index, but then you must be sure that the insert query takes the columns in same order as you are inserting in the datatable.

The AutoGenerateColumns property of the grid works in this way only, although in reverse order


这篇关于如何将数据从数据表保存到数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆