工作中为减少对数据库的写入次数,才用SqlBulkCopy对数据进行插入。需要获取表的结构。
获取表结构的代码如下:
1 public static DataTable getTableSchema(string tableName) 2 { 3 DataTable dt = new DataTable(); 4 5 string sql = "SELECT syscolumns.name,systypes.name as datatype,syscolumns.isnullable,syscolumns.length FROM syscolumns, systypes WHERE syscolumns.xusertype = systypes.xusertype AND syscolumns.id = object_id('" + tableName + "')"; 6 SqlCommand cmd = new SqlCommand(sql,sqlConn); 7 sqlConn.Open(); 8 SqlDataReader reader = cmd.ExecuteReader(); 9 while (reader.Read()) 10 { 11 try 12 { 13 dt.Columns.Add(new DataColumn(reader["name"].ToString(), SqlType2CsharpType(reader["datatype"].ToString()))); 14 Console.WriteLine(reader["isnullable"].ToString()); 15 } 16 catch (Exception ex) 17 { 18 Console.WriteLine(ex.Message); 19 Console.WriteLine(ex.StackTrace); 20 } 21 } 22 sqlConn.Close(); 23 return dt; 24 } 25 public static Type SqlType2CsharpType(string sqlType) 26 { 27 switch (sqlType) 28 { 29 case "bigint": 30 return typeof(Int64); 31 case "binary": 32 return typeof(Object); 33 case "bit": 34 return typeof(Boolean); 35 case "char": 36 return typeof(String); 37 case "datetime": 38 return typeof(DateTime); 39 case "decimal": 40 return typeof(Decimal); 41 case "float": 42 return typeof(Double); 43 case "image": 44 return typeof(Object); 45 case "int": 46 return typeof(int); 47 case "money": 48 return typeof(Decimal); 49 case "nchar": 50 return typeof(String); 51 case "ntext": 52 return typeof(String); 53 case "nvarchar": 54 return typeof(String); 55 case "real": 56 return typeof(Single); 57 case "smalldatetime": 58 return typeof(DateTime); 59 case "smallint": 60 return typeof(Int16); 61 case "smallmoney": 62 return typeof(Decimal); 63 case "text": 64 return typeof(String); 65 case "timestamp": 66 return typeof(Object); 67 case "tinyint": 68 return typeof(Byte); 69 case "VarBinary": 70 return typeof(Object); 71 case "varchar": 72 return typeof(String); 73 case "Variant": 74 return typeof(Object); 75 case "xml": 76 return typeof(Object); 77 default: 78 return null; 79 } 80 }
在使用SqlBulkCopy插入数据时,如果有自增长的列,在映射时去掉就好。