如何通过在C#中引用DataTable动态地在DB中创建表 [英] How do I Create a table in DB dynamically by referring a DataTable in C#

查看:178
本文介绍了如何通过在C#中引用DataTable动态地在DB中创建表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述





我有一个特定的要求是这样的,



会有在我的C#应用​​程序中的DataTable,其结构是动态的。我希望将相同的结构存储到DB中。



对于Ex:我有一个带有名称测试的DataTable,TestID和TestValue是两个DataColumns。

我想在DB中创建一个Table作为Test,并且列TestID和TestValue也会从数据表中复制数据。



因此,每当我获得数据表时,都应在数据库中创建一个新表。



此要求可以通过C#代码本身或甚至使用存储过程来完成在SQL Server中。



请帮助我。



谢谢和问候,

Mathi。

解决方案

您好Mathi,

这是一个非常大的概念要做..因为你需要小心大量验证



试试这样

首先尝试理解代码。

保持断点和尝试分析正在发生的事情并根据您的需求进行定制。

这是您需要的基本结构....



< pre lang =c#> class 计划
{

s tatic void Main( string [] args)
{
DataTable dt = new DataTable();
dt.Columns.Add( NumberColumn typeof int ));
dt.Rows.Add( 1 );
dt.Rows.Add( 2 );

string tableName = yourTableName;
string spName = sp _ + tableName;
StringBuilder createTableStatement = new StringBuilder(); // 用于创建表架构的字符串构建器
StringBuilder createInsertProcedure = new StringBuilder(); // 用于创建插入SP的字符串构建器
createTableStatement.Append( create table + tableName + );
createInsertProcedure.Append( create procedure sp _ + tableName + );

string csvColName = ,csvparams = ;
foreach (DataColumn col dt.Columns) // 迭代数据表列
{
string name = col.ColumnName;
string sqldatatype = col.DataType == typeof int )? int varchar(100); // 您必须为所有数据类型执行此条件
string eachColumn = string .Format( {0} {1},name,sqldatatype);
string eachParam = string .Format( @ {0} {1},name,sqldatatype);
createTableStatement.Append(eachColumn);
createInsertProcedure.Append(eachParam);
csvColName + = name + ;
csvparams + = @ + name + ;

}
csvColName = csvColName.Trim()。TrimEnd(' ,' );
csvparams = csvparams.Trim()。TrimEnd(' ,');
createTableStatement.Append( ); // 现在表已创建....
Console.WriteLine(createTableStatement) ; // 输出:create table yourTableName(NumberColumn int)
createInsertProcedure.Append( )作为开头插入 + tableName + );
createInsertProcedure.Append(csvColName);
createInsertProcedure.Append( )values();
createInsertProcedure.Append(csvColName);
createInsertProcedure.Append( ); // 使用此字符串创建存储过程.ADO.net
Console.WriteLine( createInsertProcedure); // 输出:创建过程sp_yourTableName(@NumberColumn int)作为开始插入
// yourTableName(NumberColumn)values(NumberColumn)

// 现在你知道了sp名称ie; sp_yourTableName
// 您可以按如下方式插入每一行
var con = new SqlConnection( < span class =code-string>你的conn字符串
);
SqlCommand cmd = new SqlCommand(spName,con);
cmd.CommandType = CommandType.StoredProcedure;
foreach (DataRow row in dt.Rows)
{
con.Open();
foreach (DataColumn col in dt.Columns)
cmd.Parameters.AddWithValue ( @ + col.ColumnName,row [col.ColumnName]);
cmd.ExecuteNonQuery();
con.Close();
}

}
}


将DataTable传递给SQL Server [ ^ ]


存储过程是浪费时间。你仍然会将mash一个'create table'语句。因此,迭代数据表中的属性并在SQL中构建一个创建表语句。



这几乎肯定是一件愚蠢的事情。您最好构建一个允许存储要存储的数据的表,并附加一列来表示数据所在的表。


Hi,

I have a specific requirement which goes like this,

There will be a DataTable in my C# application the structure of that is dynamic. I wanted that to be stored with the same structure into DB.

For Ex: I have a DataTable with Name Test and TestID and TestValue are two DataColumns in it.
I wanted in DB to create a Table as Test and with columns TestID and TestValue also copy the data as well from the data table.

So whenever I get a data Table a new table should be created in the DB.

This requirement can be done either through C# code itself or even using a stored procedure in SQL Server.

Please help me in this.

Thanks & Regards,
Mathi.

解决方案

Hi Mathi,
this is a very big concept to do..as you need to take care on tons of validation

Try like this
First try to understand the code.
keep break point and try to analyse what is happening and customize as per your needs.
this is the basic structure for your need....

class Program
{

    static void Main(string[] args)
    {
        DataTable dt = new DataTable();
        dt.Columns.Add("NumberColumn", typeof(int));
        dt.Rows.Add(1);
        dt.Rows.Add(2);

        string tableName = "yourTableName";
         string spName = "sp_" + tableName;
        StringBuilder createTableStatement = new StringBuilder(); // string builder to create table schema
        StringBuilder createInsertProcedure = new StringBuilder(); // string builder to create insert SP
        createTableStatement.Append("create table " + tableName + " ( ");
        createInsertProcedure.Append("create procedure sp_" + tableName + " (");

        string csvColName = "", csvparams = "";
        foreach (DataColumn col in dt.Columns)  // iterating the datatable columns
        {
            string name = col.ColumnName;
            string sqldatatype = col.DataType == typeof(int) ? " int " : " varchar (100) "; // this condition you have to do for all the data types
            string eachColumn = string.Format("{0} {1}", name, sqldatatype);
            string eachParam = string.Format("@{0} {1}", name, sqldatatype);
            createTableStatement.Append(eachColumn);
            createInsertProcedure.Append(eachParam);
            csvColName += name + ",";
            csvparams += "@" + name + " ,";

        }
        csvColName = csvColName.Trim().TrimEnd(',');
        csvparams = csvparams.Trim().TrimEnd(',');
        createTableStatement.Append(")"); // now the table has been created....
        Console.WriteLine(createTableStatement); //output :create table yourTableName ( NumberColumn  int )
        createInsertProcedure.Append(") as begin insert into " + tableName + " ( ");
        createInsertProcedure.Append(csvColName);
        createInsertProcedure.Append(" ) values ( ");
        createInsertProcedure.Append(csvColName);
        createInsertProcedure.Append(" )");   // use this string to create a stored procedure .ADO.net
        Console.WriteLine(createInsertProcedure); //output : create procedure sp_yourTableName (@NumberColumn  int ) as begin insert into 
        //  yourTableName ( NumberColumn ) values ( NumberColumn )

        // now you know the sp name ie; sp_yourTableName
        // you can insert each rows as follows 
        var con = new SqlConnection ("your conn string");
        SqlCommand cmd = new SqlCommand(spName ,con );
        cmd.CommandType = CommandType.StoredProcedure;
        foreach (DataRow row in dt.Rows)
        {
            con.Open();
            foreach (DataColumn col in dt.Columns)
                cmd.Parameters.AddWithValue("@" + col.ColumnName, row[col.ColumnName]);
            cmd.ExecuteNonQuery();
            con.Close();
        }

    }
}


Passing a DataTable to SQL Server[^]


A stored proc is a waste of time. You will still string mash a 'create table' statement. So, iterate over the properties in your data table and build a 'create table' statement in SQL.

This is almost certainly a stupid thing to do. You're better off building a table that allows for you to store the data you want to store, with an additional column to denote which 'table' the data is in.


这篇关于如何通过在C#中引用DataTable动态地在DB中创建表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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