数据库映射的实体类:

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. asp.net mvc学习入门

    MVC是什么? M: Model就是我们获取的网页需要的数据 V: View就是我们的aspx页面,注意这是一个不包含后台代码文件的aspx页面.(其实带有.asp.cs文件也不会有编译错误,但是这样 ...

  2. Vue2 封装的 Quill 富文本编辑器组件 Vue-Quill-Editor

    1.安装 npm install vue-quill-editor --save 2.使用 import { quillEditor } from 'vue-quill-editor' 3.组件中 & ...

  3. 利用Putty/Plink通过ssh tunnel端口转发实现FireFox和Chrome的加密代理访问

    如果需要使用远端服务器的DNS:在Firefox中about:config设置 network.proxy.socks_remote_dns ==> true 参考原文:http://think ...

  4. Java JPA通过hql语句查询数据

    import javax.persistence.PersistenceContext; import javax.persistence.Query; public class StudentSer ...

  5. BZOJ 1864: [Zjoi2006]三色二叉树 树形DP + 读入

    Description Input 仅有一行,不超过500000个字符,表示一个二叉树序列. Output 输出文件也只有一行,包含两个数,依次表示最多和最少有多少个点能够被染成绿色. 题解:本题大水 ...

  6. 连接mysql时遇到的问题

    1.报错:The server time zone value '???ú±ê×??±??' is unrecognized or represents 解决方法:在jdbc连接的url后面加上ser ...

  7. Python爬虫:HTTP协议、Requests库(爬虫学习第一天)

    HTTP协议: HTTP(Hypertext Transfer Protocol):即超文本传输协议.URL是通过HTTP协议存取资源的Internet路径,一个URL对应一个数据资源. HTTP协议 ...

  8. eas之日期控件

    日期选择框能进行日期和时间的编辑,默认情况下只能进行日期选择“××××年××月××日”,可通过调用用函数setTimeEnabled(boolean)来设置是否也有时间编辑.对日期进行编辑时,可手工直 ...

  9. eas之创建一个UI界面并对其操作

    private void BranchAddNew(ActionEvent e) {       UIContext uiContext = new UIContext(this);       ui ...

  10. 关于swift 底部工具栏图标锯齿模糊问题。

    今天在底部工具栏添加图片时发现图片模糊而且有锯齿,开始一直以为是美工给的图片有问题,后来发现是要设置两种图片: 比如  index.png(默认30 * 30),indexSelected(选中后的图 ...