Npgsql使用入门(二)【实用助手类】
数据库映射的实体类:
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使用入门(二)【实用助手类】的更多相关文章
- 【原创】NIO框架入门(二):服务端基于MINA2的UDP双向通信Demo演示
前言 NIO框架的流行,使得开发大并发.高性能的互联网服务端成为可能.这其中最流行的无非就是MINA和Netty了,MINA目前的主要版本是MINA2.而Netty的主要版本是Netty3和Netty ...
- Swift语法基础入门二(数组, 字典, 字符串)
Swift语法基础入门二(数组, 字典, 字符串) 数组(有序数据的集) *格式 : [] / Int / Array() let 不可变数组 var 可变数组 注意: 不需要改变集合的时候创建不可变 ...
- Thinkphp入门 二 —空操作、空模块、模块分组、前置操作、后置操作、跨模块调用(46)
原文:Thinkphp入门 二 -空操作.空模块.模块分组.前置操作.后置操作.跨模块调用(46) [空操作处理] 看下列图: 实际情况:我们的User控制器没有hello()这个方法 一个对象去访问 ...
- IM开发者的零基础通信技术入门(二):通信交换技术的百年发展史(下)
1.系列文章引言 1.1 适合谁来阅读? 本系列文章尽量使用最浅显易懂的文字.图片来组织内容,力求通信技术零基础的人群也能看懂.但个人建议,至少稍微了解过网络通信方面的知识后再看,会更有收获.如果您大 ...
- Yii2 数组助手类arrayHelper
数组助手类 ArrayHelper 1.什么是数组助手类 Yii 数组助手类提供了额外的静态方法,让你更高效的处理数组. a.获取值(getValue) class User { public $na ...
- C#中的特性 (Attribute) 入门 (二)
C#中的特性 (Attribute) 入门 (二) 接下来我们要自己定义我们自己的特性,通过我们自己定义的特性来描述我们的代码. 自定义特性 所有的自定义特性都应该继承或者间接的继承自Attribut ...
- Netty入门二:开发第一个Netty应用程序
Netty入门二:开发第一个Netty应用程序 时间 2014-05-07 18:25:43 CSDN博客 原文 http://blog.csdn.net/suifeng3051/article/ ...
- C#基础入门 二
C#基础入门 二 循环语句 与C语言中用法相同. continue:结束本次循环(continue)后面的代码不再执行,进入下次循环(通常与if连用). 数组 一维数组定义:int[] intArra ...
- redis入门(二)
目录 redis入门(二) 前言 持久化 RDB AOF 持久化文件加载 高可用 哨兵 流程 安装部署 配置技巧 集群 原理 集群搭建 参考文档 redis入门(二) 前言 在redis入门(一)简单 ...
随机推荐
- matlab学习使用Button Group绘制不同的正弦曲线
创建buttongroup控件---即按钮组 再添加三个radiobutton 对其设置 buttongroup控件改Title为绘制不同正弦曲线 第一个radiobutton的string改为sin ...
- luogu P1714 切蛋糕 单调队列
单调队列傻题. 考虑以 $i$ 结尾的答案 : $max(sumv_{i}-sumv_{j}),j \in [i-m,i-1]$ ($sumv_{i}$ 为前缀和) 稍微搞一搞,发现 $sumv_{i ...
- PAT_A1138#Postorder Traversal
Source: PAT A1138 Postorder Traversal (25 分) Description: Suppose that all the keys in a binary tree ...
- PAT_A1128#N Queens Puzzle
Source: PAT A1128 N Queens Puzzle (20 分) Description: The "eight queens puzzle" is the pro ...
- JDBC对MySQL数据库存储过程的调用
一.MySQL数据库存储过程: 1.什么是存储过程 存储过程(英文:Stored Procedure)是在大型数据库系统中,为了完成特定功能而编写的一组的SQL语句集.存储过程经编译存储在数据库中,用 ...
- Perl PPM安装模块
介绍一下如何使用PPM(Perl Package Manager)安装模块(必须安装了ActivePerl).打开PPM,我们看到的界面是这样的: 我们看到第二行是工具栏,从左到右,第一个是查看仓 ...
- HDU1087 - Super Jumping! Jumping! Jumping!【动态规划】
zh成功的在他人的帮助下获得了与小姐姐约会的机会,同时也不用担心被非"川大"的女票发现了,可是如何选择和哪些小姐姐约会呢?zh希望自己可以循序渐进,同时希望挑战自己的极限,我们假定 ...
- python项目开发:学员管理系统
学员管理系统 #需求: 1.用户角色:讲师/学员,登陆后根据角色不同能做的事情不同 2.讲师视图 - 管理班级,可创建班级,根据学员qq号把学员加入班级 - 可创建指定班级的上课纪录,注意一节上课纪录 ...
- Ribbon 负载均衡
一.是什么 Spring Cloud Ribbon 是基于 Netfix Ribbon 实现的一套客户端(服务的消费者)负载均衡的工具 二.用法 服务消费者工程的 pom.xml 添加如下内容 < ...
- HDU - 1310 - Digital Roots
先上题目: Digital Roots Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Othe ...