Program.cs代码:

 class Program{static void Main(string[] args){var test = new PgBulkCopyHelper<SingleBuilding>("bld_amap_gzmain");foreach (string pName in test.PropNames){Console.WriteLine("name: {0},\t\ttype: {1}", pName, test.PropInfo[pName]);}//-----------------------------------------------------------------------------------------------//定义每次插入的最大数量限制int maxNum = 1; //100000;//初始化对应的数据表DataTable dataTable = test.InitDataTable();string connectionString = "Host=localhost;Username=king;Password=wu12345;Database=dellstore";List<List<SingleBuilding>> bldsList = new List<List<SingleBuilding>>();NpgsqlPolygon plg1 = new NpgsqlPolygon(10);plg1.Add(new NpgsqlPoint(0.0, 0.0));plg1.Add(new NpgsqlPoint(6.0, -1.0));plg1.Add(new NpgsqlPoint(5.0, 3.0));plg1.Add(new NpgsqlPoint(1.0, 2.0));NpgsqlPolygon plg2 = new NpgsqlPolygon(10);plg2.Add(new NpgsqlPoint(100.0, 10.0));plg2.Add(new NpgsqlPoint(40.0, 180.0));plg2.Add(new NpgsqlPoint(190.0, 60.0));plg2.Add(new NpgsqlPoint(10.0, 60.0));plg2.Add(new NpgsqlPoint(160.0, 180.0));List<SingleBuilding> sblist1 = new List<SingleBuilding>(){new SingleBuilding(){id=System.Guid.NewGuid(),tile_x=1,         tile_y=2,         bps_gc=plg1,bps_llc=plg2,cp_gc=new NpgsqlPoint(0,0),   cp_llc=new NpgsqlPoint(100,10),  name="测试文本1",bld_floor=111,     height=22           },new SingleBuilding(){id=System.Guid.NewGuid(),tile_x=1,         tile_y=2,         bps_gc=plg1,bps_llc=plg2,cp_gc=new NpgsqlPoint(0,0),   cp_llc=new NpgsqlPoint(100,10),  name="测试文本2",bld_floor=222,     height=444     }};bldsList.Add(sblist1);using (var conn = new NpgsqlConnection(connectionString)){conn.Open();foreach (List<SingleBuilding> blds in bldsList){if (blds != null && blds.Count > 0){//填充数据test.FillDataTable(blds, dataTable);}//判断 dataTable 里面的数据量是否已经超过规定最大行数 maxNumif (dataTable.Rows.Count>maxNum){//如果是,则将 dataTable 里面的数据插入到数据库中test.BulkInsert(conn, dataTable);//清空 dataTable 中的现有数据dataTable.Clear();}}}}}public class SingleBuilding{//创建数据表的SQL语句如下:/*CREATE TABLE bld_amap_gzmain (id uuid PRIMARY KEY NOT NULL,tile_x integer,             --x index of the map tile where the building is locatedtile_y integer,             --y index of the map tile where the building is locatedbps_gc polygon NOT NULL,    --the points of the bottom outline of the building, geodetic coordinatesbps_llc polygon NOT NULL,   --the points of the bottom outline of the building, Latitude and longitude coordinatescp_gc point NOT NULL,       --the center point of the building, geodetic coordinatescp_llc point NOT NULL,      --the center point of the building, Latitude and longitude coordinatesname text,bld_floor smallint,         --the number of floors of the buildingheight real                 --the height of building);*/public Guid id { get; set; }public int? tile_x { get; set; }public int? tile_y { get; set; }public NpgsqlPolygon bps_gc { get; set; }public NpgsqlPolygon bps_llc { get; set; }public NpgsqlPoint cp_gc { get; set; }public NpgsqlPoint cp_llc { get; set; }public string name { get; set; }public short? bld_floor { get; set; }public float? height { get; set; }}

PgBulkCopyHelper.cs代码:

using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.Linq;
using System.Reflection;namespace PgBulkCopyHelper
{/// <summary>/// 用以快速将大批量数据插入到postgresql中/// </summary>/// <typeparam name="TEntity"></typeparam>public class PgBulkCopyHelper<TEntity>{/// <summary>/// TEntity的属性信息/// Dictionary(string "property_name", Type property_type)/// </summary>public Dictionary<string, Type> PropInfo { get; set; }/// <summary>/// TEntity的属性名称列表/// </summary>public List<string> PropNames { get; set; }/// <summary>/// 数据表全名:schema.tableName or tableName/// </summary>public string FullTableName { get; set; }/// <summary>/// 构造函数/// </summary>/// <param name="schema">数据表的schema,一般为public</param>/// <param name="tableName">数据表的名称</param>public PgBulkCopyHelper(string schema, string tableName){PropNames = new List<string>();PropInfo = new Dictionary<string, Type>();PropertyInfo[] typeArgs = GetPropertyFromTEntity();foreach (PropertyInfo tParam in typeArgs){PropNames.Add(tParam.Name);PropInfo[tParam.Name] = tParam.PropertyType;}if (!string.IsNullOrWhiteSpace(tableName)){if (string.IsNullOrWhiteSpace(schema)){FullTableName = tableName;}elseFullTableName = string.Format("{0}.{1}", schema, tableName);}}/// <summary>/// 构造函数/// </summary>/// <param name="tableName">数据表的名称</param>public PgBulkCopyHelper(string tableName):this(null, tableName){ }/// <summary>/// 获取TEntity的属性信息/// </summary>/// <returns>TEntity的属性信息的列表</returns>private PropertyInfo[] GetPropertyFromTEntity(){Type t = typeof(TEntity);PropertyInfo[] typeArgs = t.GetProperties();return typeArgs;}/// <summary>/// 根据TEntity的属性信息构造对应数据表/// </summary>/// <returns>只有字段信息的数据表</returns>public DataTable InitDataTable(){DataTable dataTable = new DataTable();foreach(PropertyInfo tParam in GetPropertyFromTEntity()){Type propType = tParam.PropertyType;//由于 DataSet 不支持 System.Nullable<> 类型,因此要先做判断if ((propType.IsGenericType) && (propType.GetGenericTypeDefinition() == typeof(Nullable<>)))propType = propType.GetGenericArguments()[0];dataTable.Columns.Add(tParam.Name, propType);}return dataTable;}/// <summary>/// 根据TEntity可枚举列表填充给定的数据表/// </summary>/// <param name="entities">TEntity类型的可枚举列表</param>/// <param name="dataTable">数据表</param>public void FillDataTable(IEnumerable<TEntity> entities, DataTable dataTable){if (entities != null && entities.Count() > 0){foreach (TEntity entity in entities){FillDataTable(entity, dataTable);}}}/// <summary>/// 在DataTable中插入单条数据/// </summary>/// <param name="entity">具体数据</param>/// <param name="dataTable">数据表</param>public void FillDataTable(TEntity entity, DataTable dataTable){var dataRow = dataTable.NewRow();int colNum = dataTable.Columns.Count;PropertyInfo[] typeArgs = GetPropertyFromTEntity();for (int i = 0; i < colNum; i++){dataRow[i] = typeArgs[i].GetValue(entity);}dataTable.Rows.Add(dataRow);}/// <summary>/// 通过PostgreSQL连接把dataTable中的数据整块填充到数据库对应的数据表中/// 注意,该函数不负责NpgsqlConnection的创建、打开以及关闭/// </summary>/// <param name="conn">PostgreSQL连接</param>/// <param name="dataTable">数据表</param>public void BulkInsert(NpgsqlConnection conn, DataTable dataTable){var commandFormat = string.Format(CultureInfo.InvariantCulture, "COPY {0} FROM STDIN BINARY", FullTableName);using (var writer = conn.BeginBinaryImport(commandFormat)){foreach (DataRow item in dataTable.Rows)writer.WriteRow(item.ItemArray);}}}
}

运行结果如图:


转载于:https://www.cnblogs.com/Wulex/p/6953527.html

Npgsql使用入门(三)【批量导入数据】相关推荐

  1. 微信小程序云开发——常用功能2:操作云数据库一键批量导入数据(导入json文件)

    微信小程序云开发--常用功能2:操作云数据库一键批量导入数据(导入json文件) 今天我们要添加100条数据.下面的过程是先创建一条记录,然后导出这条数据看json文件中是如何编辑字段的,然后仿照这个 ...

  2. 批量导入数据将word文档转换成HTML文档

    1.在批量导入数据里:第一步下载一个word文档模板,用户可以根据这个worm文档模板的要求去填写数据,填学好数据之后保存worm文档 2.在页面选择到word文档保存到from表单中,通过ajaxS ...

  3. 《项目经验》--简单三层使用DataTable向数据库表批量导入数据---向SqlServer多张张表中导入数据

    前面已经介绍过如何向数据库的一张表中批量导入数据,详情见博客<项目经验---简单三层使用DataTable向数据库表批量导入数据---向SqlServer一张表中导入数据>:本文主要介绍如 ...

  4. 怎么接收layui上传的文件_layui 上传文件_批量导入数据UI的方法

    使用layui的文件上传组件,可以方便的弹出文件上传界面. 效果如下: 点击[批量导入]按钮调用js脚本importData(config)就可以实现数据上传到服务器. 脚本: /*** * 批量导入 ...

  5. tp5大数据批量导入mysql_TP5框架下MySQL通过LOAD DATA INFILE批量导入数据详细操作

    LOAD DATA INFILE 语句用法 参考手册 本文语句参数使用默认值 PHP: TP框架环境// 定义文件路径 $file_path = 'LOAD_DATA_LOCAL_INFILE.txt ...

  6. neo4j批量导入数据的两种解决方案

    neo4j批量导入数据的两种解决方案 参考文章: (1)neo4j批量导入数据的两种解决方案 (2)https://www.cnblogs.com/YoungF/p/11632488.html 备忘一 ...

  7. tp5 excel 导入 mysql_TP5框架下MySQL通过LOAD DATA INFILE批量导入数据详细操作

    LOAD DATA INFILE 语句用法 参考手册 本文语句参数使用默认值 PHP: TP框架环境// 定义文件路径 $file_path = 'LOAD_DATA_LOCAL_INFILE.txt ...

  8. 使用python向Redis批量导入数据

    1.使用pipeline进行批量导入数据.包含先使用rpush插入数据,然后使用expire改动过期时间 class Redis_Handler(Handler):def connect(self): ...

  9. 批量导入数据到mssql数据库的

    概述 批量导入数据到数据库中,我们有好几种方式. 从一个数据表里生成数据脚本,到另一个数据库里执行脚本 从EXCEL里导入数据 上面两种方式,导入的数据都会生成大量的日志.如果批量导入5W条数据到数据 ...

  10. 随笔编号-09 批量导入数据(Mysql)报MySQL server has gone away 问题的解决方法

    问题场景: 使用*.sql 脚本,批量导入数据到mysql实例中,使用DOS 界面导入的,期间,到最后一步 source D:\aaa.sql  回车后,系统提示 MySQL server has g ...

最新文章

  1. linux下rpm,yum学习
  2. 【转】Spring Bean单例与线程安全
  3. 第一次失效_特斯拉螺栓腐蚀失效分析_搜狐汽车
  4. cshtml的a标签跳转页面_朋友圈标签来了!热门流量关键词带动视频号、小程序、搜一搜...
  5. 虚拟机fedora共享_开源虚拟现实,用于电子测试的新电路板,Fedora 25,以及更多新闻
  6. ACDU活动回顾:@DBA,前辈指路不迷茫
  7. python最简单的图形编程_Python123
  8. OA系统中的HRM的发展和存在的误区,值得每一个HR学习
  9. unix域套接字UDP网络编程
  10. 图书管理系统 ——mysql数据库
  11. 人体全身骨骼神经分布图,人体骨骼神经系统图片
  12. 软件测试必须知道的精华总结
  13. rtx客户端绿化方法+组织架构更新延迟的解决方案
  14. 高效的敏捷测试第七课 自动化部署和BVT
  15. opencv-车牌识别
  16. Python爬取周杰伦的200首歌+BI可视化分析
  17. 江南爱窗帘十大品牌 | 窗帘的定做有哪些技巧和注意事项?
  18. upc 6617: Finite Encyclopedia of Integer Sequences(树的先序遍历第n/2个结点)
  19. 强制推到远程git push
  20. 新氧运营三箭齐发,带领医美行业穿越发展迷雾

热门文章

  1. 【CF#505B】Mr. Kitayuta's Colorful Graph (并查集或Floyd或BFS)
  2. 【HDU - 2570】迷瘴 (贪心,水题,排序,卡精度有坑)
  3. java什么时候创建进程,Java创建进程
  4. vue项目编写html,从头搭建、编写一个VUE项目
  5. 面试题之实现1分2分5分组成2角问题
  6. 在JSP页面中输出JSON格式数据
  7. 关系数据库——mysql数据类型大总结
  8. 刷机提示图像和设备不匹配_安卓5.0升级失败如何解决 安卓5.0刷机失败解决方法介绍【教程】...
  9. Java基础——Java异常处理机制
  10. 紧急不代表重要:管理时间的六个秘密