博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
把DataTable导入SqlServer中
阅读量:6846 次
发布时间:2019-06-26

本文共 6467 字,大约阅读时间需要 21 分钟。

  hot3.png

首先是建表

public static string CreateTable(string tableName, System.Data.DataTable table)        {            string sqlsc;            sqlsc = "CREATE TABLE " + tableName + "(";            for (int i = 0; i < table.Columns.Count; i++)            {                sqlsc += "\n" + table.Columns[i].ColumnName;                if (table.Columns[i].DataType.ToString().Contains("System.Int32"))                    sqlsc += " int ";                else if (table.Columns[i].DataType.ToString().Contains("System.DateTime"))                    sqlsc += " datetime ";                else if (table.Columns[i].DataType.ToString().Contains("System.String"))                    sqlsc += " nvarchar(" + table.Columns[i].MaxLength.ToString() + ") ";                else if (table.Columns[i].DataType.ToString().Contains("System.Single"))                    sqlsc += " single ";                else if (table.Columns[i].DataType.ToString().Contains("System.Double"))                    sqlsc += " double ";                else                    sqlsc += string.Format(" nvarchar( {0} ) ", table.Columns[i].MaxLength == -1 ? "max" : table.Columns[i].MaxLength.ToString());                if (table.Columns[i].AutoIncrement)                    sqlsc += " IDENTITY(" + table.Columns[i].AutoIncrementSeed.ToString() + "," + table.Columns[i].AutoIncrementStep.ToString() + ") ";                if (!table.Columns[i].AllowDBNull)                    sqlsc += " NOT NULL ";                sqlsc += ",";            }            return sqlsc + ")";        }        ///         /// Creates a SQL script that creates a table where the columns matches that of the specified DataTable.        ///         public static string BuildCreateTableScript(DataTable Table)        {            StringBuilder result = new StringBuilder();            result.AppendFormat("CREATE TABLE [{1}] ({0}   ", Environment.NewLine, Table.TableName);            bool FirstTime = true;            foreach (DataColumn column in Table.Columns.OfType
()) { if (FirstTime) FirstTime = false; else result.Append(" ,"); result.AppendFormat("[{0}] {1} {2} {3}", column.ColumnName, // 0 GetSQLTypeAsString(column.DataType), // 1 column.AllowDBNull ? "NULL" : "NOT NULL", // 2 Environment.NewLine // 3 ); } result.AppendFormat(") ON [PRIMARY]{0}GO{0}{0}", Environment.NewLine); // Build an ALTER TABLE script that adds keys to a table that already exists. if (Table.PrimaryKey.Length > 0) result.Append(BuildKeysScript(Table)); return result.ToString(); } ///
/// Builds an ALTER TABLE script that adds a primary or composite key to a table that already exists. /// private static string BuildKeysScript(DataTable Table) { // Already checked by public method CreateTable. Un-comment if making the method public // if (Helper.IsValidDatatable(Table, IgnoreZeroRows: true)) return string.Empty; if (Table.PrimaryKey.Length < 1) return string.Empty; StringBuilder result = new StringBuilder(); if (Table.PrimaryKey.Length == 1) result.AppendFormat("ALTER TABLE {1}{0} ADD PRIMARY KEY ({2}){0}GO{0}{0}", Environment.NewLine, Table.TableName, Table.PrimaryKey[0].ColumnName); else { List
compositeKeys = Table.PrimaryKey.OfType
().Select(dc => dc.ColumnName).ToList(); string keyName = compositeKeys.Aggregate((a, b) => a + b); string keys = compositeKeys.Aggregate((a, b) => string.Format("{0}, {1}", a, b)); result.AppendFormat("ALTER TABLE {1}{0}ADD CONSTRAINT pk_{3} PRIMARY KEY ({2}){0}GO{0}{0}", Environment.NewLine, Table.TableName, keys, keyName); } return result.ToString(); } ///
/// Returns the SQL data type equivalent, as a string for use in SQL script generation methods. /// private static string GetSQLTypeAsString(Type DataType) { switch (DataType.Name) { case "Boolean": return "[bit]"; case "Char": return "[char]"; case "SByte": return "[tinyint]"; case "Int16": return "[smallint]"; case "Int32": return "[int]"; case "Int64": return "[bigint]"; case "Byte": return "[tinyint] "; case "Byte[]": return "[varbinary] (max)"; case "UInt16": return "[smallint] "; case "UInt32": return "[int] "; case "UInt64": return "[bigint] "; case "Single": return "[float]"; case "Double": return "[double]"; case "Decimal": return "[decimal]"; case "DateTime": return "[datetime]"; case "Guid": return "[uniqueidentifier]"; case "Object": return "[variant]"; case "String": return "[nvarchar](max)"; default: throw new Exception( "未处理的类型" + DataType.Name ) ; } } }

然后是批量导入

private void SqlBulkCopyByDatatable(string connectionString, string TableName, DataTable dt)        {            dt = CreateDataTable();            using (SqlConnection conn = new SqlConnection(connectionString))            {                using (SqlBulkCopy sqlbulkcopy = new SqlBulkCopy(connectionString, SqlBulkCopyOptions.UseInternalTransaction))                {                    try                    {                        sqlbulkcopy.DestinationTableName = TableName;                        for (int i = 0; i < dt.Columns.Count; i++)                        {                            sqlbulkcopy.ColumnMappings.Add(dt.Columns[i].ColumnName, dt.Columns[i].ColumnName);                        }                        sqlbulkcopy.WriteToServer(dt);                        //textBox3.Text = "导入成功,记录数 " + dt.Rows.Count;                    }                    catch (System.Exception ex)                    {                        //tabControl1.SelectedIndex = 1;                        //textBox3.Text = ex.Message + "\r\n\r\n" + ex.StackTrace;                    }                }            }        }

转载于:https://my.oschina.net/sqhua/blog/537304

你可能感兴趣的文章
superdic cracked by TK
查看>>
开发人员需要熟知的常用Linux命令之七:Gzip及其常用打包、压缩、解压命令
查看>>
转一个打包程序教程
查看>>
Android -----listView的属性大全
查看>>
快速排序算法之我见(附上C代码)
查看>>
FineUI参考手册(离线版)现已免费提供下载!
查看>>
Nginx+Windows负载均衡(转载)
查看>>
[推荐]ORACLE PL/SQL编程之四:把游标说透(不怕做不到,只怕想不到)
查看>>
优化IPOL网站中基于DCT(离散余弦变换)的图像去噪算法(附源代码)。
查看>>
微软最有价值专家大中华峰会花絮视频
查看>>
Chapter 1 First Sight——25
查看>>
64bit Centos6.4搭建hadoop-2.5.1
查看>>
前端开发必备!Emmet使用手册
查看>>
node-load module
查看>>
前端性能优化策略
查看>>
Clion使用MinGW编译好的boost库
查看>>
c#超时锁定
查看>>
Android 自定义View实现多行RadioGroup (MultiLineRadioGroup)
查看>>
mac office
查看>>
Leetcode: Valid Word Abbreviation
查看>>