前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >SqlBulkCopy – The given value of type String from the data source cannot be converted to type

SqlBulkCopy – The given value of type String from the data source cannot be converted to type

作者头像
全栈程序员站长
发布2022-09-09 13:35:13
8130
发布2022-09-09 13:35:13
举报
文章被收录于专栏:全栈程序员必看

大家好,又见面了,我是你们的朋友全栈君。

SqlBulkCopy – The given value of type String from the data source cannot be converted to type of the specified target column

针对使用C#SqlBulkCopy对象遇到的问题总结 1.批量插入excel数据遇到的类型转换问题 2.去除非数据行

以下是对应的解决办法及代码 1.批量插入数据报错两种可能,第一填写字段对应关系的时候可能有重复的,第二是数据的字段长度不足(这个需要注释一些字段然后慢慢放开注释找到出错的字段) 2.第二个直接上代码 注:ColumnMapping 是自己手动创建的excel列名与数据库对应表的列名一一对应的类

代码语言:javascript
复制
/// <summary>
        /// 
        /// </summary>
        /// <param name="P_str_Excel">excel file name</param>
        /// <param name="P_str_SheetName"></param>       
        public void ImportDataToSql(string P_str_Excel, string DestinationTableName, ColumnMappingCollection collectionMapping, bool ifClearContent = false)
        {
            //DataSet myds = new DataSet();                               //创建数据集对象
            try
            {
                string P_str_SheetName = GetSheetName(P_str_Excel)[0];
                //获得全部数据
                string P_str_OledbCon;
                if (Environment.Is64BitOperatingSystem == false)
                    P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
                else
                    P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
                OleDbConnection oledbcon = new OleDbConnection(P_str_OledbCon);     //创建Oledb数据库连接对象
                string P_str_ExcelSql;                             //记录要执行的Excel查询语句
                OleDbDataAdapter oledbda = null;                            //创建Oledb数据桥接器对象
                P_str_ExcelSql = string.Format("select * from [{0}$]", P_str_SheetName);    //记录要执行的Excel查询语句
                oledbda = new OleDbDataAdapter(P_str_ExcelSql, P_str_OledbCon);     //使用数据桥接器执行Excel查询

                DataTable importedTable = new DataTable();
                importedTable.Columns.Clear();

                oledbda.Fill(importedTable);                            //填充数据

                if (ifClearContent)
                {
                    //清楚非内容行
                    ColumnMapping firstColumn = collectionMapping.FindbyFileIndex(0);
                    List<DataRow> deleteList = new List<DataRow>();
                    foreach (DataRow item in importedTable.Rows)
                    {
                        if (item[0].ToString() != firstColumn.FileFieldName)
                            item.Delete();
                        else
                            break;
                    }

                    int i = 0;
                    foreach (var item in collectionMapping)
                    {
                        importedTable.Columns[i].Caption = item.FileFieldName;
                        importedTable.Columns[i].ColumnName = item.FileFieldName;
                        i++;
                    }

                    importedTable.AcceptChanges();
                    oledbda.Update(importedTable);
                }

                using (SqlBulkCopy bcp = new SqlBulkCopy(ConnectString))         //用bcp导入数据
                {
                    bcp.BatchSize = 100;                                //每次传输的行数
                    bcp.DestinationTableName = DestinationTableName;             //定义目标表
                    foreach (var item in collectionMapping)
                    {
                        bcp.ColumnMappings.Add(item.FileFieldName, item.DataColumnName);
                    }
                    
                    bcp.WriteToServer(importedTable);                      //将数据写入Sql Server数据表
                }
            }
            catch(Exception ex)
            {
                throw ex;
            }
        }

        private List<string> GetSheetName(string P_str_Excel)                           //获取所有工作表名称
        {
            List<string> P_list_SheetName = new List<string>();                     //创建泛型集合对象
            string P_str_OledbCon;
            if (Environment.Is64BitOperatingSystem == false)
                P_str_OledbCon = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 8.0;HDR=Yes;IMEX=2\"";
            else
                P_str_OledbCon = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + P_str_Excel + ";Extended Properties=\"Excel 12.0;HDR=Yes;IMEX=2\"";
            OleDbConnection olecon = new OleDbConnection(P_str_OledbCon);                                         //连接Excel数据库
            olecon.Open();                                              //打开数据库连接
            System.Data.DataTable DTable = olecon.GetSchema("Tables");                  //创建表对象
            DataTableReader DTReader = new DataTableReader(DTable);                 //创建表读取对象
            while (DTReader.Read())                                     //循环读取
            {
                string P_str_Name = DTReader["Table_Name"].ToString().Replace('$', ' ').Trim(); //记录工作表名称
                if (!P_list_SheetName.Contains(P_str_Name))                     //判断泛型集合中是否已经存在该工作表名称
                    P_list_SheetName.Add(P_str_Name);                           //将工作表名添加到泛型集合中
            }
            DTable = null;                                              //清空表对象
            DTReader = null;                                            //清空表读取对象
            olecon.Close();                                             //关闭数据库连接
            return P_list_SheetName;                                        //返回得到的泛型集合
        }

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/162226.html原文链接:https://javaforall.cn

本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • SqlBulkCopy – The given value of type String from the data source cannot be converted to type of the specified target column
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档