数据库映射的实体类:

public class Test
{
public long TestID { get; set; }
public string Name { get; set; }
public int Age { get; set; }
}

 public class TestLink
{
public int TestLinkID { get; set; }
public long TestID { get; set; }
public string LinkName { get; set; }
}

 public class customer
{
public long customer_id { get; set; }
public int age { get; set; }
public string name { get; set; }
}

 public class order
{
public int order_id { get; set; }
public int customer_id { get; set; }
public string item { get; set; }
public string shipping_address { get; set; }
}

 /// <summary>
/// 实体 company
/// </summary>
[Description("Primary:id")]
[Serializable]
public class Company
{ #region 私有变量
private Int32 _id = Int32.MinValue;
private string _name = null;
private Int32 _age = Int32.MinValue;
private string _address = null;
private float _salary = float.MinValue;
private DateTime _join_date = DateTime.MinValue;
#endregion #region 公共属性
/// <summary>
/// 主键 id(NOT NULL)
/// </summary>
public Int32 id
{
set { _id = value; }
get { return _id; }
}
/// <summary>
/// name(NOT NULL)
/// </summary>
public string name
{
set { _name = value; }
get { return _name; }
}
/// <summary>
/// age(NOT NULL)
/// </summary>
public Int32 age
{
set { _age = value; }
get { return _age; }
}
/// <summary>
/// address
/// </summary>
public string address
{
set { _address = value; }
get { return _address; }
}
/// <summary>
/// salary
/// </summary>
public float salary
{
set { _salary = value; }
get { return _salary; }
}
/// <summary>
/// join_date
/// </summary>
public DateTime join_date
{
set { _join_date = value; }
get { return _join_date; }
}
#endregion }

Program.cs代码:

 public class Program
{
static void Main(string[] args)
{
using (var dc = new NpgSqlDataContext("Host=localhost;Username=king;Password=wu12345;Database=dellstore").MapComposite<Company>("company"))
{
var r0 = dc.Query(@"SELECT * FROM company");
PrintTable(r0); //------------------------------------------------------------------------------------------------- var r1 = dc.Query(@"SELECT * FROM company where id=@id", new NpgsqlParameter("id", 3));
PrintTable(r1);
//------------------------------------------------------------------------------------------------- // 使用表值参数
// Postgres 没有tvp - 它们由正则或复合类型的数组
var r3 = dc.Query(@" SELECT c.* FROM company c INNER JOIN UNNEST(@ageval_tvp) tvp ON c.age = tvp", new NpgsqlParameter("ageval_tvp", new int[] { 1,3, 4}));
PrintTable(r3);
//------------------------------------------------------------------------------------------------- // 复合型tvp
dc.MapComposite<Company>("company");
var r4 = dc.Query(@" SELECT c.* FROM company c INNER JOIN UNNEST(@x_company) x ON c.age = x.age AND c.name = x.name",
new NpgsqlParameter(
"x_company",
new Company[] {
new Company() { name = "Paul", age = 32 },
new Company() { name = "Allen", age = 25 }
}
)
);
PrintTable(r4);
//------------------------------------------------------------------------------------------------- dc.MapComposite<order>("orders");
var r6 = dc.Query(@"INSERT INTO orders (order_id,customer_id, item,shipping_address) SELECT order_id,customer_id, item,shipping_address from UNNEST(@x_orders) returning order_id",
new NpgsqlParameter(
"x_orders",
new order[] {
new order() {order_id=1, customer_id = 22, item = "cc",shipping_address="加利福尼亚硅谷1号" },
new order() {order_id=2,customer_id = 23, item = "dd",shipping_address="中国上海外滩18号" }
})
);
PrintTable(r6);
//------------------------------------------------------------------------------------------------- //Console.ReadKey(); var r7 = dc.Execute(@"WITH customer as (insert into customers(name, age) values ('Ghan', 55) returning customer_id)INSERT INTO orders(customer_id, item)SELECT c.customer_id, x.item FROM customer c CROSS JOIN UNNEST(@x_orders) x
",
new NpgsqlParameter(
"x_orders",
new order[] {
new order() { item = "gg" },
new order() { item = "hh" }
}
)
);
Console.WriteLine("Inserted {0} rows", r7); //------------------------------------------------------------------------------------------------- //区分大小写的名称
var query = @"
WITH Customer AS (INSERT INTO ""Test"" (""Name"", ""Age"")
SELECT ""Name"", ""Age""
FROM UNNEST(@TestItems) returning ""TestID"")
INSERT INTO ""TestLink"" (""TestID"")
SELECT c.""TestID"" FROM Customer c
"; var query1 = @"
WITH Customer AS (INSERT INTO ""Test"" (""Name"", ""Age"")
SELECT ""Name"", ""Age""
FROM UNNEST(@TestItems) returning ""TestID"")
INSERT INTO ""TestLink"" (""TestID"", ""LinkName"")
SELECT c.""TestID"", x.""LinkName"" FROM Customer c CROSS JOIN UNNEST (@TestLinkItems) x
"; var x = dc.Execute(query,new NpgsqlParameter("TestItems", new Test[] { new Test() { Name = "Sam", Age = 25 } })); Console.WriteLine("已插入行 {0}", x);
//------------------------------------------------------------------------------------------------- var y = dc.Execute(query1,
new NpgsqlParameter(
"TestItems",
new Test[] { new Test() { Name = "Sam", Age = 25 } }),
new NpgsqlParameter(
"TestLinkItems",
new TestLink[]
{
new TestLink() {LinkName = "xxx"},
new TestLink() {LinkName = "yyy"}
})); Console.WriteLine("已插入行 {0}", y); }
Console.ReadKey();
} static void PrintTable(DataTable t)
{
foreach (var c in t.Columns.Cast<DataColumn>().Select(r => r.ColumnName))
Console.Write("{0,12}", c);
Console.WriteLine(); foreach (var r in t.Rows.Cast<DataRow>())
{
foreach (var c in r.ItemArray)
{
int length=c.ToString().Length;
Console.Write("{0,12}", length > 10 ? c.ToString().Substring(0, 10) : c.ToString());
} Console.WriteLine();
}
Console.WriteLine("\n");
Console.WriteLine("-----------------------------------------------------------------------------");
}
}

CaseSensitiveTranslator.cs代码:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql; namespace NpgSqlUtils
{
public class CaseSensitiveTranslator : INpgsqlNameTranslator
{
public string TranslateMemberName(string clrName)
{
return clrName;
} public string TranslateTypeName(string clrName)
{
return clrName;
}
}
}

INpgSqlDataContext.cs代码:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Npgsql; namespace NpgSqlUtils
{
public interface INpgSqlDataContext: IDisposable
{
INpgsqlNameTranslator Translator { get; }
DataTable Query(string query, params NpgsqlParameter[] parameters);
int Execute(string query, params NpgsqlParameter[] parameters); /// <summary>
///
/// </summary>
INpgSqlDataContext MapComposite<T>(string name) where T : new();
}
}

NpgSqlDataContext.cs代码:

using Npgsql;
using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Threading.Tasks; namespace NpgSqlUtils
{
public class NpgSqlDataContext : INpgSqlDataContext
{
private NpgsqlConnection _connection; public INpgsqlNameTranslator Translator { get; set; } public NpgSqlDataContext(string connectionString, INpgsqlNameTranslator translator = null)
{
if (translator == null)
translator = new CaseSensitiveTranslator(); Translator = translator; _connection = new NpgsqlConnection(connectionString);
_connection.Open();
} public DataTable Query(string query, params NpgsqlParameter[] parameters)
{
DataTable result;
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = _connection;
cmd.CommandText = query;
cmd.Parameters.AddRange(parameters); using (var reader = cmd.ExecuteReader())
{
result = new DataTable();
result.Load(reader);
}
} return result;
} public int Execute(string query, params NpgsqlParameter[] parameters)
{
int result = -1;
using (NpgsqlCommand cmd = new NpgsqlCommand())
{
cmd.Connection = _connection;
cmd.CommandText = query;
cmd.Parameters.AddRange(parameters);
result = cmd.ExecuteNonQuery();
} return result;
} public void Dispose()
{
_connection.Dispose();
} public INpgSqlDataContext MapComposite<T>(string name) where T : new()
{
_connection.MapComposite<T>(name, Translator);
return this;
}
}
}

SQL脚本:

-- Table: public.company

-- DROP TABLE public.company;

CREATE TABLE public.company
(
id integer NOT NULL,
name text COLLATE pg_catalog."default" NOT NULL,
age integer NOT NULL,
address character(50) COLLATE pg_catalog."default",
salary real,
join_date date,
CONSTRAINT company_pkey PRIMARY KEY (id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default; ALTER TABLE public.company
OWNER to postgres;

-- Table: public.orders

-- DROP TABLE public.orders;

CREATE TABLE public.orders
(
order_id integer NOT NULL,
shipping_address text COLLATE pg_catalog."default",
item text COLLATE pg_catalog."default",
customer_id integer,
CONSTRAINT orders_pkey PRIMARY KEY (order_id)
)
WITH (
OIDS = FALSE
)
TABLESPACE pg_default; ALTER TABLE public.orders
OWNER to postgres;

运行结果如图:



Npgsql使用入门(二)【实用助手类】的更多相关文章

  1. 【原创】NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示

    前言 NIO框架的流行,使得开发大并发.高性能的互联网服务端成为可能.这其中最流行的无非就是MINA和Netty了,MINA目前的主要版本是MINA2.而Netty的主要版本是Netty3和Netty ...

  2. Swift语法基础入门二(数组, 字典, 字符串)

    Swift语法基础入门二(数组, 字典, 字符串) 数组(有序数据的集) *格式 : [] / Int / Array() let 不可变数组 var 可变数组 注意: 不需要改变集合的时候创建不可变 ...

  3. Thinkphp入门 二 —空操作、空模块、模块分组、前置操作、后置操作、跨模块调用(46)

    原文:Thinkphp入门 二 -空操作.空模块.模块分组.前置操作.后置操作.跨模块调用(46) [空操作处理] 看下列图: 实际情况:我们的User控制器没有hello()这个方法 一个对象去访问 ...

  4. IM开发者的零基础通信技术入门(二):通信交换技术的百年发展史(下)

    1.系列文章引言 1.1 适合谁来阅读? 本系列文章尽量使用最浅显易懂的文字.图片来组织内容,力求通信技术零基础的人群也能看懂.但个人建议,至少稍微了解过网络通信方面的知识后再看,会更有收获.如果您大 ...

  5. Yii2 数组助手类arrayHelper

    数组助手类 ArrayHelper 1.什么是数组助手类 Yii 数组助手类提供了额外的静态方法,让你更高效的处理数组. a.获取值(getValue) class User { public $na ...

  6. C#中的特性 (Attribute) 入门 (二)

    C#中的特性 (Attribute) 入门 (二) 接下来我们要自己定义我们自己的特性,通过我们自己定义的特性来描述我们的代码. 自定义特性 所有的自定义特性都应该继承或者间接的继承自Attribut ...

  7. Netty入门二:开发第一个Netty应用程序

    Netty入门二:开发第一个Netty应用程序 时间 2014-05-07 18:25:43  CSDN博客 原文  http://blog.csdn.net/suifeng3051/article/ ...

  8. C#基础入门 二

    C#基础入门 二 循环语句 与C语言中用法相同. continue:结束本次循环(continue)后面的代码不再执行,进入下次循环(通常与if连用). 数组 一维数组定义:int[] intArra ...

  9. redis入门(二)

    目录 redis入门(二) 前言 持久化 RDB AOF 持久化文件加载 高可用 哨兵 流程 安装部署 配置技巧 集群 原理 集群搭建 参考文档 redis入门(二) 前言 在redis入门(一)简单 ...

随机推荐

  1. iOS安全策略之HTTPS

    1.HTTPS传输流程 2.常用加密算法 3.AFN证书校验策略及核心方法 4.SSL Pinning 5.CA证书申请流程 HTTPS经由超文本传输协议进行通信,但利用SSL/TLS来对数据包进行加 ...

  2. luogu P1856 [USACO5.5]矩形周长Picture 扫描线 + 线段树

    Code: #include<bits/stdc++.h> #define maxn 200007 #define inf 100005 using namespace std; void ...

  3. eas之获取各模块系统状态信息

    public void getSystemStatue() throws EASBizException, BOSException    {        CompanyOrgUnitInfo co ...

  4. 配置Jupyter

    前几天见同学有用Jupyter notebook的,有点喜欢,于是今天自己配了一下. Jupyter是一个非常好用编辑器,因为Jupyter notebook 不仅可以编写代码运行,并且可以直接在代码 ...

  5. Centos 7.x 源码编译搭建Nginx

    环境: centos 7 防火墙关闭 Selinx关闭 Nginx Web安装 安装依赖库 yum install pcre-devel pcre gcc gcc-c++ zlib zlib-deve ...

  6. python-写入csv 文件

    项目要做一个导出客户信息的功能,需要写入csv: 注意文件写入的方式  例如   write open(‘w’) 从头开始写,之前写的会被替换  write open(‘a’) 则代表追加,文件指针放 ...

  7. php去除h5标签

    function html2text($str){  $str = preg_replace("/<style .*?<\\/style>/is", " ...

  8. python 图片滑动窗口

    METHOD #1: No smooth, just scaling. def pyramid(image, scale=1.5, minSize=(30, 30)): # yield the ori ...

  9. js实现的时间轴效果

    今天整理以前的资料发现以前写的一个时间轴效果,当时也是网上找了很久没有找到,就自己写了一个,现在发出来给有需要的人,代码写的可能有点乱. 效果图: 下面是美工做的设计图的效果(有个美工就是好): 下面 ...

  10. oracle到mysql的导数据方式(适用于任意数据源之间的互导)

    http://www.wfuyu.com/Internet/19955.html 为了生产库释放部份资源, 需要将API模块迁移到mysql中,及需要导数据. 尝试了oracle to mysql工具 ...