PostgreSQL安装及空间数据

Npgsql: 用户的手册

Copyright© The Npgsql Development Team

 

 

Lastupdate: $Date: 2009/12/20 02:33:47 $ by $Author: fxjr $

Category:External documentation

IntendedAudience: Npgsql Users

1. What is Npgsql?

Npgsql 是一个.net的资料提供者为postgresql的数据库服务器

它允许一个.net客户端应用程序(控制台,WinForms,ASP的。网络、网络服务…)发送和接收数据与postgresql的服务器。它正在积极开发基于指南规定在.net文档。

2. How to get and compile Npgsql 如何获得和编译Npgsql

2.1 Binary package  二进制包

你可以下载Npgsql编译为MS . 在里面编写.net的项目。

这个包裹里,你会发现下面的目录的布局。

Npgsql/bin/docs- Documentation

Npgsql/bin/docs/apidocs- API Documentation

Npgsql/bin/ms1.1- Npgsql compiled for MS.Net 1.1

Npgsql/bin/mono- Npgsql compiled for Mono

As soonas Npgsql is released on other platforms/versions, they will be addedaccordingly to this layout.

2.2 Installing binary package 安装二进制包

为了查找到。net运行时,文件Npgsql.dll必须放置在你的应用程序目录——除非你指定另一个目录作为通往私营成分通过一个配置文件(使用探测单元)。请看看。net除有关如何运行(位于)总成,被载入。确切地说,前面可以称为” 通往私人组件"

在ASP。网络和网络服务的应用程序中,必须有一个叫做“bin”的应用与ASP.net目录. 举例来说,如果应用程序目录被称为“ASPNETApplication”,然后Npgsql.dll和Mono.Security.dll必须放置在“ASPNETApplication \bin”的目录. 如果这些文件是不正确的目录,你可以看到编译器生成错误代码,使用Npgsql类。

或者,你可以把Npgsql装配在解决。自从版本0.4,Npgsql强烈签字——这意味着你可以用“gacutil "安装它。

下列命令:

 gacutil - Npgsql.dll

 

请参阅“安装装配在全球缓存汇编”部分的单据MSDN来获得更多信息.利用gac的意义,你应该充分理解,沿着这条路。

  注意,放置在……要求Npgsql设计时间支持.net可视化工作室。

  (Npgsql编制单声道不需要Mono.Security.dll作为已经融入单声道运行。)

  一旦你拷贝或设置组件,你准备去试试这个例子——跳转到section 3.

2.3 Getting Npgsql from CVS  获得Npgsql到CVS

让Npgsql到CVS,使用下列资料储存在你的客户信息

Server:cvs.pgfoundry.org

Repository:/cvsroot/npgsql

Modulename: Npgsql2

User:anonymous

Password:

If youare using CVS from a command line, use this command:

cvs -d:pserver:anonymous@cvs.pgfoundry.org:/cvsroot/npgsql login

 

Hit theEnter key when prompted for a password (none required):

cvs -d:pserver:anonymous@cvs.pgfoundry.org:/cvsroot/npgsql checkout Npgsql2

 

The codewill begin transferring:

$ cvs -d:pserver:anonymous@cvs.pgfoundry.org:/cvsroot/npgsql login

Logging in to:pserver:anonymous@cvs.pgfoundry.org:2401/cvsroot/npgsql

CVS password:

$ cvs -d:pserver:anonymous@cvs.pgfoundry.org:/cvsroot/npgsql co Npgsql2

cvs checkout:Updating Npgsql2

cvs checkout:Updating Npgsql2/admin

UNpgsql2/admin/release.pl

cvs checkout:Updating Npgsql/docs

UNpgsql2/docs/Npgsql.zargo

UNpgsql2/docs/NpgsqlConnectionStateMachine.png

UNpgsql2/docs/SuggestedReadings.htm

...

 

2.4 Compiling Npgsql  编译Npgsql

官方支持Npgsql编制方法是0.86版本. 版本0.86是必要的,因为它已经支持编译颗卫星资源总成。

仅仅从Npgsql /src/ Npgsql文件夹。它将创建一个文件夹名为“build”,看到了“build / ms”文件夹中产生的组件。

我们也有项目文件为MonoDevelop、视觉工作室网络和可视化工作室.net2008年。

2.5 Running Npgsql Unit tests  Npgsql运行单元测试

为了能够跑nunit测试,你必须首先设置你的测试数据库。

首先,创建一个数据库称为npgsql_tests:

createdbnpgsql_tests

 

再来,创建一个用户称为npgsql_tests与密码:

createuser -NPnpgsql_tests

 

现在,运行脚本加表、功能、数据等。这些脚本是位于testsuite / noninteractive文件夹。

nUnit运行测试,简单地跑。

 

3. Npgsql Usage  Npgsql用法

这部分解释了Npgsql使用.net应用程序中(窗口或net)。如果你是一个有经验的数据访问应用程序中使用Sql服务器、OleDB或ODBC网络供应商,你会发现Npgsql与其非常相似,在很多方面同样或具有更强的鲁棒性,并由一个活跃的社区。

为了使用Npgsql,p ostgresql的服务器必须遵守TCP / IP协议。 TCP协议是默认在8.0级+服务器。以前的版本应该开始以“-i”选项。检查详情: http://www.postgresql.org/docs/7.4/static/postmaster-start.html

注:Npgsql仍处于发展阶段。只会显示当前支持特征。作为Npgsql日趋成熟,会有更多的功能。

Adding required namespaces to your source file  添加到源文件要求的命名空间

首先,要获得到Npgsql对象(如下)。Intellisense在.net可视化工作室),需要指示编译器使用Npgsql命名空间。当你操纵数据反演,课程体系Npgsql…数据还将被调用。在c#,加上这个指令到适当的网页或类:

using System.Data;

using Npgsql;

 

如果你正在使用ASP.NET,你可能需要添加下列代码在你的ASPX页。

<%@ Assemblyname="System.Data" %>

<%@ Assemblyname="Npgsql" %>

在这里,你可以读到更多的细节FAQMono Page about ASP.NET

Establishing a connection  建立连接

Toestablish a connection to a server located at IP 127.0.0.1, port 5432, as user"joe", with password "secret", on database"joedata", open NpgsqlConnection with the following connectionstring:

建立一个连接到服务器的IP 127.0.0.1,端口号:5432 用户“joe”, 密码资料库” secret”,打开NpgsqlConnection 下面的连接字符串:

using System;

using System.Data;

using Npgsql;

 

public classNpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");

    conn.Open();

    conn.Close();

  }

}

 

Connection String parameters  连接字符串参数

  当建立连接,NpgsqlConnection接受许多参数改变其行为。这里是目前已有的参数可以修改:(到NpgsqlConnection数据源)。

  [本主题是字符串用来连接到一个postgresql的数据库。

有效的价值观是:

ServerAddress/name  postgresql的服务器连接到ProtocolProtocol版本使用,而不是自动的; DatabaseDatabase整数2或3名。默认的用户名如果不指定用户名SecuritySet IdUser综合使用windows综合安全. 默认为文本PasswordPassword =false 认证SSLTrue或false。控制是否尝试一个安全的联系。默认Pooling=false  true或false 。控制是否连接池中使用。真实大小的默认= MinPoolSizeMin 连接池。敏油藏规模,如果用户指定,会使NpgsqlConnection pre-allocate指定数量的连接的服务器。默认的:1 MaxPoolSizeMax连接池的大小。混合时将被处理掉的连接池的返回包含超过这个数字池的连接。20 EncodingObsolete违约。总是返回字符串"Unicode”,静静地忽视试图把它。TimeoutTime等待连接打开,在几秒钟。默认是15人。CommandTimeoutTime等待命令执行之前完成抛出一个异常。在几秒钟内。默认是20。Sslmode ssl连接控制模式。可以是下列之一:PreferIf是可能的,经SLL SSL连接将被使用。RequireIf SSL连接是不能成立的,是一个例外。AllowNot支持;没有SSL连接。DisableNo SSL连接。缺省值是“关闭”。如果Npgsql SyncNotificationSpecifies应该使用同步通知SearchPathChanges搜索路径来指定和公共模式。. Preload Reader

如果被设置为true(默认值是“false”),这导致datareaders装载之前,在整体ExecuteReader回报。这个结果在较少的性能(特别是在非常大,在这种情况下,recordsets性能可能无法忍受的水平),但是是一种选项来掩盖独特潜能backwards-compatibility问题Npgsql以前的版本。

根据ADO . 网络文档,而一个IDataReader是打开IDbConnection用来获取是“忙”,不能用于其他操作(几个文件的例外)。Npgsql执行这个规则,因此而开放的NpgsqlDataReader大多数其他的操作NpgsqlConnection用来获得它会导致一个InvalidOperationException(Npgsql松弛的规则允许你使用一个连接,如果一个NpgsqlDataReader一直读到最后,它的产生(s),即使它没有被关闭,因为这时不再使用任何资源的连接.

Npgsql先前用户能够完全忽略了这条规则。这完全是一个副作用的内部实施等问题,并严格来说一直支持(因为它总是违反ADO . 网络规范),但是你应该会一点点安慰,忽然发现以前工作的代码被打破了。因此,如果你找到一个问题,这种改变,你可以使用这个connection-string选择回到以前的行为。

如果你确实需要使用,应该这样做作为权宜之计定价之前代码的问题,有两个原因:

1.    性能,特别是可没有这个选项要好得多。

2.    这样的代码将会失败,你应该在任何时候想扩大到支持不同的资料提供者。

 

利用扩展的类型

此选项会影响DataAdaptors是否使用.net体系期望…货期的类型或Npgsql日期和时间,如NpgsqlTimeStamp类型具有的功能和范围的System.DateTime。要么选项允许的类型和系统Npgsql被使用,但如果设置为true DataAdaptors期望能通过特定的Npgsql类型的问题,而如果设置为false,他们将预期System.DateTime

这个选项是实验性的,可望其影响将减少或删除,在以后的版本。

默认值为"false".

兼容性

这个版本是将其作为一个简单的处理方法变化来增加更多突破和连接字符串选项。它以一种形式的版本号(a.b[[c.d])。改变现有的代码将会休息,在可能的情况下,复制行为的前的版本号。第一个这样的版本是2.0.2.1,所以“2.0.2”不会有新的行为。

 

Version

Behaviour

2.0.2

1.    如果字段名是没有找到, GetOrdinal将返回- 1。

2.    GetOrdinal是kana-width灵敏

2.0.2.1

1.    如果字段名是没有找到, GetOrdinal必将IndexOutOfRangeException。

2.    GetOrdinal是kana-width迟钝。

Using NpgsqlCommand to add a row in a table  使用NpgsqlCommand在表里添加行

前面的例子不做任何有用的。它仅仅是连接到数据库断开连接。如果有一个错误,一个NpgsqlException被抛出。现在,假设你有一个表称为“表”两大领域,“fielda”和“fieldb”,两种类型为int。如果你想插入元组(1):1)在这张表里,你可以把插入语句。using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");

    conn.Open();

 

    NpgsqlCommand command = newNpgsqlCommand("insert into table1 values(1, 1)", conn);

    Int32 rowsaffected;

 

    try

    {

      rowsaffected = command.ExecuteNonQuery();

      Console.WriteLine("It was added {0}lines in table table1", rowsaffected);

    }

    finally

    {

      conn.Close();

    }

  }

}

 ExecuteNonQuery()是适合插入、更新查询,因为它返回整数表示的受上次操作。

Getting a single result value using the NpgsqlCommand.ExecuteScalar()method   

获得一个结果值使用NpgsqlCommand.ExecuteScalar()方法

在某些情况下,你只需要找回单值(标量),从功能。使用ExecuteScalar()方法,对一个指令对象:

using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

    conn.Open();

 

    NpgsqlCommand command = new NpgsqlCommand("selectversion()", conn);

    String serverversion;

 

    try

    {

      serverversion =(String)command.ExecuteScalar();

      Console.WriteLine("PostgreSQL serverversion: {0}", serverversion);

    }

    finally

    {

      conn.Close();

    }

  }

}

你也可以使用ExecuteScalar再次对查询字段,如“select count(*) from table1”。然而,当调用函数返回的一套一个或多个记录,只有第一个专栏的第一个条目返回(DataSet.Tables[0]],[[0 .Rows 0])。一般来说,有任何查询返回的值应该被称为Command.ExecuteScalar。

Getting a full result set with NpgsqlCommand.ExecuteReader() method andNpgsqlDataReader

得到结果集NpgsqlCommand.ExecuteReader()方法和NpgsqlDataReader

有几种方法可以返回recordsets与Npgsql。当你想通过一个SQL语句是命令文本和存取的memory-efficent DataReader,使用ExecuteReader()方法的NpgsqlCommand对象:using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

    conn.Open();

 

    NpgsqlCommand command = newNpgsqlCommand("select * from tablea", conn);

 

    try

    {

NpgsqlDataReader dr = command.ExecuteReader();

while(dr.Read())

{

  __for (i = 0;i < dr.FieldCount; i++)

  __{

 ___Console.Write("{0} \t", dr[i]);

  __}

 __Console.WriteLine();

}

    }

    finally

    {

      conn.Close();

    }

  }

}

 Note that you can 'daisy chain' selectstatements in a command object's commandtext to retrieve more than one recordset: "select * from tablea; select * from tableb"

Using parameters in a query  利用参数查询

让你dynamcially参数插入到SQL查询的价值观的运行时间。一般说来,参数约束的最好办法是建立动态SQL语句在你的代码。其他的方法,如基本字符串连接,越来越少的鲁棒性和可vulerable到SQL注入攻击。加到你的SQL查询字符串参数的paramter名字的前缀,以“:”。下面的例子使用了参数(see ":value1")。

using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

    public static void Main(String[] args)

    {

        using(NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;"))

        {

            conn.Open();

 

            // Declare the parameter in thequery string

            using(NpgsqlCommand command = newNpgsqlCommand("select * from tablea where column1 = :value1", conn))

            {

 

                // Now add the parameter to theparameter collection of the command specifying its type.

                command.Parameters.Add(newNpgsqlParameter("value1", NpgsqlDbType.Integer));

 

                // Now, add a value to it andlater execute the command as usual.

                command.Parameters[0].Value =4;

 

                using(NpgsqlDataReader dr =command.ExecuteReader())

                {

                    while(dr.Read())

                    {

                        for (i = 0; i <dr.FieldCount; i++)

                        {

                           Console.Write("{0} \t", dr[i]);

                        }

                        Console.WriteLine();

                    }

                }

            }

        }

    }

}

 

您也可以发一个参数查询到服务器使用NpgsqlParamenter和NpgsqlParamenterCollection物体。)这个代码假定一个表称为“称至少有一个专栏”命名为" column1”式的int4。

Using prepared statements  使用准备报告

在准备方法让你优化性能的常用的疑问。Prepare ()的主要“缓存"查询计划,这样就可以用在随后的电话。(注意:这个功能才可在服务器7.3 +版本。如果你叫它在一个服务器不支持它,Npgsql会静静地忽视它。)简单地叫准备()方法的NpgsqlCommand前查询过程。

using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

    public static void Main(String[] args)

    {

        using(NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;"))

        {

            conn.Open();

 

            // Declare the parameter in thequery string

            using(NpgsqlCommand command = newNpgsqlCommand("select * from tablea where column1 = :column1", conn))

            {

                // Now add the parameter to theparameter collection of the command specifying its type.

                command.Parameters.Add(newNpgsqlParameter("column1", NpgsqlDbType.Integer);

 

                // Now, prepare the statement.

                command.Prepare();

 

                // Now, add a value to it andlater execute the command as usual.

                command.Parameters[0].Value =4;

 

                using(NpgsqlDataReader dr =command.ExecuteReader())

                {

                    while(dr.Read())

                    {

                        for (i = 0; i <dr.FieldCount; i++)

                        {

                            Console.Write("{0}\t", dr[i]);

                        }

                        Console.WriteLine();

                    }

                }

            }

        }

    }

}

这个代码假定一个表称为“称至少有一个专栏”命名为" column1”式的int4。

Function calling  函数呼叫

呼叫函数, 把CommandType财产的CommandType NpgsqlCommand对象.StoredProcedure和传球的名字,你想叫作为函数的返回查询字符串(CommandText property)。

using System;

using System.Data;

using Npgsql;

 

//下面的例子使用了funcC函数定义()

// 创建 function funcC() 返回整数'

// select count(*)from tablea;

// ' language'sql';

 

//注:返回类型的选择(*)的改变,从int4到int8在7.3 +版本。使用这个函数

//在一个7.2服务器,改变了对int4从int8返回类型。

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

    conn.Open();

 

    try

    {

        NpgsqlCommand command = newNpgsqlCommand("funcC", conn);

        command.CommandType =CommandType.StoredProcedure;

 

        Object result =command.ExecuteScalar();

 

        Console.WriteLine(result);

    }

    finally

    {

      conn.Close();

    }

  }

}

 

添加参数到postgresql的功能类似于我们先前的例子。然而,当指定返回字符串时,你可以排除参数的名字。使用函数的名称。

using System;

using System.Data;

using Npgsql;

 

//下面的例子使用了funcC函数

// create functionfuncC(int4) returns int8 as '

// select count(*)from tablea where field_int4 = $1;

// ' language'sql';

 

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

    conn.Open();

 

    try

    {

        NpgsqlCommand command = newNpgsqlCommand("funcC", conn);

        command.CommandType =CommandType.StoredProcedure;

 

        __command.Parameters.Add(newNpgsqlParameter());

        command.Parameters[0].NpgsqlDbType =NpgsqlDbType.Integer;

        command.Parameters[0].Value = 4;

 

        Object result =command.ExecuteScalar();

 

        Console.WriteLine(result);

    }

    finally

    {

      conn.Close();

    }

  }

}

 

这个代码假定一个表称为“称至少有一场”,被称为“field_int4”式的int4。

Getting full results in a DataSet object: Using refcursors  结果得到充分的数据对象:使用 refcursors

Refcursors是最有效的方法来建造功能,返回的结果集Postgres给客户端。使用refcursors单一功能,可以返回结果查询到客户端在一个单一的来回票。大多数Npgsql开发商知道refcursors非常容易使用,一旦你掌握了基本的语法。这两种结果集样本返回从功能使用refcursors。Npgsql一致的支持refcursor,你可以得到很多的结果集,而不必担心内部refcursorPostgres的运作。

考虑以下refcursor-based功能:

CREATE OR REPLACEFUNCTION testrefcursor(int4) RETURNS SETOF refcursor AS

 

'DECLARE

  ref1 refcursor;

  ref2 refcursor;

  ref3 refcursor;

BEGIN

 

OPEN ref1 FOR

 SELECT * FROM table1;

RETURN NEXT ref1;

 

OPEN ref2 FOR

 SELECT * FROM table2;

RETURN next ref2;

 

OPEN ref3 FOREXECUTE

 'SELECT * FROM table3 WHERE keyfield = ' ||$1;

RETURN next ref3;

 

RETURN;

END;'

LANGUAGE plpgsql;

 

这个函数将返回三个选择语句结果。值得注意的是,最后选择声明动态创建服务器上。

现在,这些功能和检索数据使用DataReader时,你应该用下面的代码:

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

 

public class c

{

    public static void Main(String[] args)

    {

 

        NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Initial Catalog=eeeeee;Userid=npgsql_tests;password=npgsql_tests;");

        conn.Open();

 

        NpgsqlTransaction t =conn.BeginTransaction();         

        NpgsqlCommand command = newNpgsqlCommand("testrefcursor", conn);

        command.CommandType =CommandType.StoredProcedure;

 

        NpgsqlDataReader dr =command.ExecuteReader();

 

        while(dr.Read())

        {

 

            Console.WriteLine(dr.GetValue(0));

        }

 

        dr.NextResult();

 

        while(dr.Read())

        {

 

            Console.WriteLine(dr.GetValue(0));

        }

        dr.Close();

        t.Commit();

        conn.Close();

    }

}

 

或者,你可以检索结果变成一个数据对象

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

 

public class c

{

    public static void Main(String[] args)

    {

        DataSet myDS;

        NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Initial Catalog=eeeeee;Userid=npgsql_tests;password=npgsql_tests;");

        conn.Open();

 

        NpgsqlTransaction t =conn.BeginTransaction();         

        NpgsqlCommand command = newNpgsqlCommand("testrefcursor", conn);

        command.CommandType = CommandType.StoredProcedure;

 

        con.Open();

        NpgsqlDataAdapter da = newNpgsqlDataAdapter(command);

        da.Fill(myDS);

 

        t.Commit();

        conn.Close();

    }

}

 

就是这样!”。最后一件事值得一提的是,你必须用一种交易为了使这项工作。这是有必要的, 预防指针返回通过refcursor功能关闭后的implicity交易完成,(你做的呼叫函数)。

如果你在你的函数参数,只给函数的名字和添加参数返回财产的NpgsqlCommand参数采集像往常一样。Npgsql管理你正确的参数约束。

Using output parameters in a query  采用输出参数在一个查询

输出参数,可以用Npgsql。注意Npgsql“simulates”输出参数分解了第一个结果集执行查询和翻译它输出参数值。这可以在两个方面:一是映射。一个映射解析 试配以列名返回到一个参数产生同样的名字。如果找到匹配的,只有输出参数有比赛将被更新。如果一个地图是没有找到,输出参数进行更新,以他们添加到命令参数采集。该映射是自动的。在分析产生,Npgsql试图找到了一个相配的。输出和InputOutput参数方向都支持。

using System;

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

    public static void Main(String[] args)

    {

        NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

        conn.Open();

 

        // Send a query to backend.

        NpgsqlCommand command = newNpgsqlCommand("select * from tablea where column1 = 2", conn);

 

        // Now declare an output parameter toreceive the first column of the tablea.

 

        NpgsqlParameter firstColumn = newNpgsqlParameter("firstcolumn", NpgsqlDbType.Integer);

        firstColumn.Direction =ParameterDirection.Output;

 

        command.Parameters.Add(firstColumn);

 

        try

        {

            command.ExecuteNonQuery();

 

            // Now, the firstcolumn parameterwill have the value of the first column of the resultset.

           Console.WriteLine(firstColumn.Value);

        }

        finally

        {

            conn.Close();

        }

    }

}

 

Working with .NET Datasets   工作和。net的数据集

Npgsql让你相依的改变.net的数据对象到数据库。下面的例子演示了插入一个记录到的数据集,紧随其后的是一个叫更新相关数据库:

// This methodexpects the following table in the backend:

//

//_create tabletableb(field_int2 int2, field_timestamp timestamp, field_numeric numeric);

//

//_

voidAddWithDataSet(NpgsqlConnection conn)

{_

conn.Open();

DataSet ds = newDataSet();

NpgsqlDataAdapterda = new NpgsqlDataAdapter("select * from tableb", conn);

 

da.InsertCommand =new NpgsqlCommand("insert into tableb(field_int2, field_timestamp,field_numeric) " + " values (:a, :b, :c)", conn);

da.InsertCommand.Parameters.Add(newNpgsqlParameter("a", NpgsqlDbType.Smallint));

da.InsertCommand.Parameters.Add(newNpgsqlParameter("b", NpgsqlDbType.Timestamp));

da.InsertCommand.Parameters.Add(newNpgsqlParameter("c", NpgsqlDbType.Numeric));

 

da.InsertCommand.Parameters[0].Direction= ParameterDirection.Input;

da.InsertCommand.Parameters[1].Direction= ParameterDirection.Input;

da.InsertCommand.Parameters[2].Direction= ParameterDirection.Input;

da.InsertCommand.Parameters[0].SourceColumn= "field_int2";

da.InsertCommand.Parameters[1].SourceColumn= "field_timestamp";

da.InsertCommand.Parameters[2].SourceColumn= "field_numeric";

 

da.Fill(ds);

DataTable dt =ds.Tables[0];

 

DataRow dr =dt.NewRow();

dr["field_int2"]= 4;

dr["field_timestamp"]= new DateTime(2003, 03, 03, 14, 0, 0);

dr["field_numeric"]= 7.3M;

 

dt.Rows.Add(dr);

DataSet ds2 =ds.GetChanges();

da.Update(ds2);

ds.Merge(ds2);

ds.AcceptChanges();

}

 

 

Working with strongly typed datasets  处理数据工作

这个例子演示了使用一种强烈的输入的数据所产生的将来预留的。开始时,我们需要一个将来预留的文件specifing有效的方案。你可以生成这个文件,或者你可以用一个将来预留的工具来产生。为了让NpgsqlDataAdapter产生将来预留,你需要供应和XML文件中,XML文件的推理的允许XML格式。

public voidGenerateXmlFromDataSet(NpgsqlConnection conn)

{

conn.Open();

 

NpgsqlDataAdapterda = new NpgsqlDataAdapter("select * from tablea", conn);

DataSet ds = newDataSet();

da.Fill(ds);

ds.WriteXml("StrongDataSetFeed.xml");

}

 

这个例子的结果在一个文件中,看起来相似。

<?xmlversion="1.0" standalone="yes"?>

<NewDataSet>

  <Table>

    <field_serial>1</field_serial>

    <field_text>Randomtext</field_text>

  </Table>

  <Table>

    <field_serial>2</field_serial>

    <field_int4>4</field_int4>

  </Table>

  <Table>

    <field_serial>3</field_serial>

    <field_int8>8</field_int8>

  </Table>

  <Table>

    <field_serial>4</field_serial>

    <field_bool>true</field_bool>

  </Table>

  <Table>

    <field_serial>5</field_serial>

    <field_text>Text with ' singlequote</field_text>

  </Table>

</NewDataSet>

 

 

下列命令用文件生成将来预留的

xsdStrongDataSetFeed.xml

 

XSD willproduce an XML schema in which all types are specified as string. As aconsequence, we need to change the XSD to specify the correct types, resultingin an XSD file similar to:

<?xmlversion="1.0" encoding="utf-8"?>

<xs:schemaid="NewDataSet" xmlns=""xmlns:xs="http://www.w3.org/2001/XMLSchema"xmlns:msdata="urn:schemas-microsoft-com:xml-msdata">

  <xs:element name="NewDataSet"msdata:IsDataSet="true" msdata:Locale="pt-BR">

    <xs:complexType>

      <xs:choicemaxOccurs="unbounded">

        <xs:elementname="Table">

          <xs:complexType>

            <xs:sequence>

              <xs:elementname="field_serial" type="xs:int" minOccurs="0"/>

              <xs:elementname="field_text" type="xs:string" minOccurs="0"/>

              <xs:elementname="field_int4" type="xs:int" minOccurs="0"/>

              <xs:elementname="field_int8" type="xs:long" minOccurs="0"/>

              <xs:elementname="field_bool" type="xs:boolean" minOccurs="0"/>

            </xs:sequence>

          </xs:complexType>

        </xs:element>

      </xs:choice>

    </xs:complexType>

  </xs:element>

</xs:schema>

 

鉴于上述文件,下面的指令生成一个强烈的输入数据:

xsdStrongDataSetFeed.xsd /dataset

 

这个指令生成一个文件的整理成一个装配工作的数据。产品广泛应用于下面的例子。

using System;

using Npgsql;

 

public class t

{

   public static void Main(String[] args)

   {

      NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

 

      conn.Open();

      NpgsqlDataAdapter da = newNpgsqlDataAdapter("Select * from tablea", conn);

 

      NewDataSet n = new NewDataSet();

      da.Fill(n);

 

      foreach (NewDataSet._TableRow tr inn._Table)

      {

        Console.WriteLine(tr.field_serial);

      }

   }

}

 

Working with binary data and bytea datatype  工作 二进制数据和bytea数据类型

这个样品需要一个文件名作为一个参数,将其内容到一张表被称为“tableByteA”。表格包含一场名为“field_bytea”式的bytea和一场名为“field_serial”型系列。接下来,它的内容和写作领域中一个新的文件后缀"database".

表图式理论: create table tableBytea(field_serial serial, field_bytea bytea)

 

using System;

using System.Data;

using Npgsql;

using System.IO;

 

public class t

{

  public static void Main(String[] args)

  {

    //NpgsqlEventLog.Level = LogLevel.Debug;

    //NpgsqlEventLog.LogName ="NpgsqlTests.LogFile";

    NpgsqlConnection conn = newNpgsqlConnection("server=localhost;userid=npgsql_tests;password=npgsql_tests");

    conn.Open();

 

    FileStream fs = new FileStream(args[0],FileMode.Open, FileAccess.Read);

    BinaryReader br = new BinaryReader(newBufferedStream(fs));

    Byte[] bytes =br.ReadBytes((Int32)fs.Length);

    Console.WriteLine(fs.Length);

    br.Close();

    fs.Close();

 

    NpgsqlCommand command = newNpgsqlCommand("insert into tableBytea(field_bytea)values(:bytesData)", conn);

    NpgsqlParameter param = newNpgsqlParameter(":bytesData", NpgsqlDbType.Bytea);

    param.Value = bytes;

 

    command.Parameters.Add(param);

    command.ExecuteNonQuery();

    command = new NpgsqlCommand("selectfield_bytea from tableBytea where field_serial = (select max(selectfield_serial) from tableBytea);", conn);

 

    Byte[] result =(Byte[])command.ExecuteScalar();

    fs = new FileStream(args[0] +"database", FileMode.Create, FileAccess.Write);

 

    BinaryWriter bw = new BinaryWriter(newBufferedStream(fs));

 

    bw.Write(result);

    bw.Flush();

    fs.Close();

    bw.Close();__

 

    conn.Close();

  }

}

 

Working with large object support 工作对大对象支持使用

这样品是几乎相同的bytea以上代码。它存储文件检索postgresql,然后再删除。例如用bytea示例文件,写着“database “后缀。

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

using System.IO;

 

public class c

{

    public static void Main(String[] args)

    {

        NpgsqlConnection newconn = newNpgsqlConnection("server=localhost;userid=npgsql_tests;password=npgsql_tests");

 

        newcon.Open();

        NpgsqlTransaction t =newcon.BeginTransaction();

        LargeObjectManager lbm = newLargeObjectManager(newcon);

 

        int noid =lbm.Create(LargeObjectManager.READWRITE);

        LargeObject lo =  lbm.Open(noid,LargeObjectManager.READWRITE);

 

        FileStream fs = File.OpenRead(args[0]);

 

        byte[] buf = new byte[fs.Length];

        fs.Read(buf,0,(int)fs.Length);

 

        lo.Write(buf);

        lo.Close();

        t.Commit();

 

        t = newcon.BeginTransaction();

 

        lo = lbm.Open(noid,LargeObjectManager.READWRITE);

 

        FileStream fsout =File.OpenWrite(args[0] + "database");

 

        buf = lo.Read(lo.Size());

 

        fsout.Write(buf, 0, (int)lo.Size());

        fsout.Flush();

        fsout.Close();

        lo.Close();

        t.Commit();

 

        DeleteLargeObject(noid);

 

        Console.WriteLine("noid:{0}", noid);

        newcon.Close();

    }

 

    public static void DeleteLargeObject(Int32noid)

    {

        NpgsqlConnection conn = newNpgsqlConnection("server=localhost;userid=npgsql_tests;password=npgsql_tests");

 

        newcon.Open();

        NpgsqlTransaction t =newcon.BeginTransaction();

        LargeObjectManager lbm = newLargeObjectManager(newcon);

        lbm.Delete(noid);

 

        t.Commit();

 

        newcon.Close();

    }

}

 

另一个例子是由mirek(mirek在mascort点COM点PL),大对象支持使用到从数据库中的图像显示在窗体上的客户。

 

using System;

using Npgsql;

using NpgsqlTypes;

usingSystem.Drawing;

using System.IO;

 

//metod whos 图像连接到数据库

 

public inttakeOID(int id)

{

    //这是一个metodwhos连接到数据库,并返回图像oid

 

    BazySQL pir = newBazySQL(Login.DaneUzera[8]);

    string pytanko = String.Format("selectrysunek from k_rysunki where idtowaru = " + idtowaru.ToString());

    string[] wartosci =pir.OddajSelectArray(pytanko);

    int liczba =int.Parse(wartosci[0].ToString());

    return liczba;

}

 

//从数据库转换到图像的类型

 

public ImagepobierzRysunek(int idtowaru)

{

    NpgsqlConnection Polacz = newNpgsqlConnection();

    Polacz.ConnectionString =Login.DaneUzera[8].ToString();  //itsmetod whos return connection string

    Polacz.Open();

    NpgsqlTransaction t =Polacz.BeginTransaction();

    LargeObjectManager lbm = newLargeObjectManager(Polacz);

    LargeObject lo =lbm.Open(takeOID(idtowaru),LargeObjectManager.READWRITE); //take picture oidfrom metod takeOID

    byte[] buf = new byte[lo.Size()];

    buf = lo.Read(lo.Size());

    MemoryStream ms = new MemoryStream();

    ms.Write(buf,0,lo.Size());

    lo.Close();

    t.Commit();

    Polacz.Close();

    Polacz.Dispose();

    Image zdjecie = Image.FromStream(ms);

    return zdjecie;

}

 

//接着我用这个方法

 

pictureBox1.Image= Image pobierzRysunek(1);

 

Retrieving last inserted id on a table with serial values   找回最后的标识一个表中的序列值

这个例子是由乔希在论坛回答一用户问题。假定本代码表和功能在你npgsql数据库中:

create tabletest_seq (field_serial serial, test_text text);

 

 CREATE OR REPLACE FUNCTIONins_seq("varchar")

        RETURNS test_seq AS

        'insert into test_seq (test_text)values ($1);

        select * from test_seq where test_text= $1'

        LANGUAGE 'sql' VOLATILE;

 

这是代码:

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

 

public class c

{

    public static void Main(String[] args)

    {

        //NpgsqlEventLog.Level =LogLevel.Debug;

        //NpgsqlEventLog.LogName ="NpgsqlTests.LogFile";

        //NpgsqlEventLog.EchoMessages = true;

 

        NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;");

 

        using (NpgsqlDataAdapter adapter = newNpgsqlDataAdapter("select * from test_seq", conn))

        {

            DataTable table = new DataTable();

            adapter.Fill(table);

            adapter.InsertCommand = newNpgsqlCommand("ins_seq", adapter.SelectCommand.Connection);

           adapter.InsertCommand.Parameters.Add("foo",NpgsqlTypes.NpgsqlDbType.Varchar, 100, "test_text");

            adapter.InsertCommand.CommandType =CommandType.StoredProcedure;

 

            DataRow row = table.NewRow();

            row["test_text"] ="asdfqwert";

            table.Rows.Add(row);

            adapter.Update(table);

 

            foreach (DataRow rowItem in table.Rows)

            {

                Console.WriteLine("key{0}, value {1}", rowItem[0], rowItem[1]);

            }

 

            Console.ReadLine();

        }

    }

}

 

Cancelling a command in progress  取消命令

npgsql可以让服务器取消命令。为此,我们取消npgsqlcommand的方法。注意另一个线程必须处理的请求作为主要的线程将堵塞等命令。此外,主要的线程将异常结果的用户注销。(错误代码57014。)看下面的代码演示了这个技术:

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

usingSystem.Threading;

 

public class c

{

//此方法要求下表中后端:

    //

    /*     CREATE OR REPLACE FUNCTION funcwaits() returns integer as

    '

    declare t integer;

    begin

 

    t := 0;

 

    while t < 1000000 loop

    t := t + 1;

    end loop;

 

    return t;

    end;

    '

    */

 

    static NpgsqlConnection conn = null;

    static NpgsqlCommand command = null;

 

    public static void Main(String[] args)

    {

        //NpgsqlEventLog.Level =LogLevel.Debug;

        //NpgsqlEventLog.LogName ="NpgsqlTests.LogFile";

        //NpgsqlEventLog.EchoMessages = true;

 

        try

        {

          conn = new NpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;");

          conn.Open();

 

          NpgsqlCommand d = newNpgsqlCommand();

          Thread t = new Thread(newThreadStart(CancelRequest));

          command = newNpgsqlCommand("select * from funcwaits()", conn);

          Console.WriteLine("Cancellingcommand...");

          t.Start();

         Console.WriteLine(command.ExecuteScalar());

          conn.Close();

        }

        catch(NpgsqlException e)

        {

                if (e.Code == "57014")

                       Console.WriteLine("Command was cancelled");

        }

    }

 

    public static void CancelRequest()

    {

        command.Cancel();

        Console.WriteLine("commandcancelled");

    }

}

 

 

Working with Notifications   工作与通知

Npgsql允许用户接受事件基于发出通知服务器。有两种方法来获得notications与Npgsql:同步或不同步。同步通知Npgsql只支持1.0以上。

Asynchronous notifications   异步通知

这是默认的通报机制在npgsql。它被称为异步因为npgsql没有收到通知在执行,它在服务器上产生. npgsql收到通知在客户端交互的服务器。这种交互实际上发生在Npgsql发送一个后续的命令,服务器-这可能由几秒到几小时后。在这种情况下,大多数用户需要积极投票服务器为了得到及时通知。投票的方式之一,包括通过空指令,如";"

Synchronous notifications  同步通知

从Npgsql 1.0,有支持同步通知。当工作在这种模式下,Npgsql能够获得notificaton在它的实例化并交付给客户。所有这一切都是没有任何附加的顾客和服务器之间的交互作用(如上所述)。

重要的通知: 当使用同步通知,在你的通知不能执行命令处理程序的功能。如果你这样做,你就会落npgsql作线,负责通知的一样,处理npgsql和后端。如果你想使用任何命令,请创建一个连接,使用它。这不是最好的解决办法,我们要研究更好的办法去解决,而不需要一个连接。

这个代码与通知是相同的模式:

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

usingSystem.Threading;

 

public class c

{

    public static void Main(String[] args)

    {

        conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;");

        conn.Open();

 

        NpgsqlCommand command = newNpgsqlCommand("listen notifytest;", conn);

        command.ExecuteNonQuery();

 

        conn.Notification += newNotificationEventHandler(NotificationSupportHelper);

 

        command = newNpgsqlCommand("notify notifytest;", _conn);

        command.ExecuteNonQuery();

 

        Console.ReadLine();  // To prevent program termination beforenotification is handled.

    }

 

    private void NotificationSupportHelper(Objectsender, NpgsqlNotificationEventArgs args)

    {

        // process notification here.

    }

}

 

这个代码声明一个通知,并有参数传递到NotificationSupportHelper方法。

Fast bulk data copy into a table 大量的数据复制到表

批插入大量数据会耗费大量时间。postgresql提供一种选择,很快的插入数据。它的语法和输入格式选项已经解释了在postgresql的拷贝文件。复制数据从客户端到需要使用的选项。

在直接拷贝运行时文件, 你提供的数据进行编码的使用相同的服务器。

最简单的方法是,提供可读档案的copyin操作。在构造函数,这份工作就会读的东西都流到了服务器。 (提交一份声明中的文档不同的输入格式!)

1.    你看SyncNotification =true 的在您的数据库连接字符串。这是抓住任何异常报告在进口以防止顾客和服务器之间的僵局网络缓冲器。

2.    创建NpgsqCopyIn对象提供数据流输入数据库

3.    开始复制操作。工作完毕

4.    如果开始()将抛出异常,NpgsqlCopyIn.Cancel()取消一项持续的操作和清晰的连接回到准备查询的状态。否则你的连接可以呆在复制模式,不能做别的事情。

using System;

using System.Data;

using Npgsql;

 

public classCopyInExample

{

 

    public static void Main(String[] args)

    {

 

        conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;SyncNotification=true;");

        conn.Open();

 

        NpgsqlCommand command = newNpgsqlCommand("COPY myCopyTestTable FROM STDIN", conn);

        NpgsqlCopyIn cin = new NpgsqlCopyIn(command, conn, Console.OpenStandardInput() ); // expecting input in serverencoding!

        try

        {

            cin.Start();

        }

        catch(Exception e)

        {

            try

            {

                cin.Cancel("Undocopy");

            }

            catch(NpgsqlException e2)

            {

                // we should get an error inresponse to our cancel request:

                if( !(""+e2).Contains("Undo copy") )

                {

                    throw newException("Failed to cancel copy: " + e2 + " upon failure:" + e);

               

            }

            throw e;

        }

    }

}

 

如果你愿意提供的数据从你的应用程序,你可以用正常的输入流:

1.    你看SyncNotification =true 的在您的数据库连接字符串。这是抓住任何异常报告在进口以防止顾客和服务器之间的僵局网络缓冲器。  

2.    创建NpgsqCopyIn对象提供数据流输入数据库  

3.    开始复制操作。工作完毕

4.    写数据的格式和编码成 npgsqlcopyin.copystream

5.    在连接期间不能用于任何其他事情。

6.    叫copystream。close()或npgsqlcopyin。end()完成写作

7.    取消一项持续的操作和清晰的联系,准备回电话查询状态NpgsqlCopyIn.Cancel()。

8.    Upon failure callNpgsqlCopyIn.Cancel() to cancel an ongoing operation and clear connection backto Ready For Query state. Otherwise your connection may stay in copy mode,unusable for anything else.

using System;

using System.Data;

using Npgsql;

 

public classCopyInExample

{

 

    public static void Main(String[] args)

    {

 

        conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;SyncNotification=true;");

        conn.Open();

 

        NpgsqlCommand command = newNpgsqlCommand("COPY myCopyTestTable FROM STDIN", conn);

        NpgsqlCopyIn cin = new NpgsqlCopyIn(command, conn );

 

        Stream inStream =Console.OpenStandardInput();

        Encoding inEncoding =System.Text.Encoding.ASCII;

        Encoding serverEncoding =System.Text.Encoding.BigEndianUnicode; // example assumption

 

        try

        {

            cin.Start();

            Stream copyInStream =cin.CopyStream;

            byte[] buf = new byte[9];

            int i;

            while( (i =inStream.Read(buf,0,buf.Length)) > 0 )

            {

                buf = System.Text.Convert(inEncoding, serverEncoding, buf, 0, i );

                copyInStream.Write( buf, 0, i);

            }

            copyInStream.Close(); // orcin.End(), if you wish

        }

        catch(Exception e)

        {

            try

            {

                cin.Cancel("Undocopy"); // Sends CopyFail to server

            }

            catch(Exception e2)

            {

                // we should get an error inresponse to our cancel request:

                if( !(""+e2).Contains("Undo copy") )

                {

                    throw new Exception("Failedto cancel copy: " + e2 + " upon failure: " + e);

                }

            }

            throw e;

        }

    }

}

 

Fast bulk data copy from a table or select 快速复制表内数据

即使是鸡毛蒜皮的零件的大型数据集可以成为耗时的网络瓶颈. 过提供了另一种方法,更快的取出的原始数据. 它的语法和输入格式选项已经解释了PostgreSQL COPY documentation. 拷贝数据到客户端需要使用到stdout.选项

把服务器端提供的数据进行编码:

最简单的方法是提供一个可写的CopyOut操作构造函数。在开始时,操作将每件事写下来,从服务器到接收器(参阅文件副本声明不同的输出格式!)

1.     npgsqcopyout对象创建了一书写输出从数据库

2.    叫start()开始复制操作。所有要求的数据输入流。

3.    进行操作可能会被取消,copystream。close()或npgsqlcopyin。

4.    end()在您的连接失败时,你不能取消这个副本操作。

5.    如果start()抛出了异常,取消正在运行。否则你的连接可以呆在复制模式,不能做别的事情.

using System;

using System.Data;

using Npgsql;

 

public classCopyOutExample

{

 

    public static void Main(String[] args)

    {

 

        conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;");

        conn.Open();

 

        NpgsqlCommand command = newNpgsqlCommand("COPY myCopyTestTable TO STDOUT", conn);

        NpgsqlCopyOut cout = new NpgsqlCopyOut(command, conn, Console.OpenStandardOutput() );

        try

        {

            cout.Start();

        }

        catch(Exception e)

        {

            try

            {

                cout.End(); // returnconnection to Ready for Query state

            }

            catch(Exception e2)

            {

                throw newException("Failed to revive from copy: " + e2 + " upon failure:" + e);

            }

            throw e;

        }

    }

}

 

You canread COPY OUT data normally from a stream:

1.    创建对象

2.    调用Start()  开始复制操作

3.    从服务器读取数据编码NpgsqlCopyOutCopyStream或从NpgsqlCopyOut.Read

4.    在操作连接不可以使用任何别的东西

5.     All data has been received when no more comesout (CopyStream.Read(...) returns zero; NpgsqlCopyOut.Read a null pointer)

6.    操作在结束时自动完成

7.    一个持续的操作可能会呼叫CopyStream.Close()或NpgsqlCopyIn.End()。

8.    持续运转。失败取消否则你的连接可以呆在复制模式,不能做别的事情

using System;

using System.Data;

using Npgsql;

 

public classCopyOutExample

{

 

    public static void Main(String[] args)

    {

        conn = newNpgsqlConnection("Server=127.0.0.1;User id=npgsql_tests;password=npgsql_tests;");

        conn.Open();

 

        NpgsqlCommand command = newNpgsqlCommand("COPY myCopyTestTable TO STDOUT", conn);

        NpgsqlCopyOut cout = new NpgsqlCopyOut(command, conn );

 

        Stream outStream = Console.OpenStandardOutput();

        Encoding serverEncoding =System.Text.Encoding.BigEndianUnicode; // example assumption

        Encoding outEncoding =System.Text.Encoding.ASCII;

 

        try

        {

            cout.Start();

            Stream copyOutStream =cout.CopyStream;

            byte[] buf = cout.Read; // completefirst row

           Console.Out.Write(buf,0,buf.Length);

            int i;

            while( (i =copyOutStream.Read(buf,0,buf.Length)) > 0 )

            {

                buf = System.Text.Convert(serverEncoding, outEncoding, buf, 0, i );

                Console.Out.Write( buf, 0, i );

            }

            copyOutStream.Close(); // orcout.End(), if you wish

        }

        catch(Exception e)

        {

            try

            {

                cout.End(); // returnconnection to Ready for Query state

            }

            catch(Exception e2)

            {

                throw newException("Failed to revive from copy: " + e2 + " upon failure:" + e);

            }

            throw e;

        }

    }

}

 

System.Transactions Support   System.Transactions交易

谢谢你,Josh Cooley .npgsql初步支持system.transactions。因为还在早期,所以如果你有什么问题,请告诉我们,我们可以尽快修理。要使用它,你必须使用下面的连接字符串:

Enlist=true

 

False iscurrently the default, but we will likely make enlist=true the default onceSystem.Transactions support stabilizes.

Here isa sample code which uses System.Transactions support:

 

using System;

using System.Data;

using Npgsql;

usingSystem.Transactions;

 

public classTransactionExample

{

 

    public static void Main(String[] args)

    {

 

            string connectionString ="Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;Enlist=true";

            using (TransactionScope tx = newTransactionScope())

            {

                using (NpgsqlConnectionconnection = new NpgsqlConnection(connectionString))

                {

                    connection.Open();

                    using (NpgsqlCommandcommand = new NpgsqlCommand("insert into tablea (cola) values ('b')",connection))

                    {

                       command.ExecuteNonQuery();

                    }

                    using (NpgsqlConnectionconnection2 = new NpgsqlConnection(connectionString))

                    {

                        connection2.Open();

                        using (NpgsqlCommandcommand = new NpgsqlCommand("insert into tablea (colb) values ('c')",connection2))

                        {

                           command.ExecuteNonQuery();

                        }

                    }

                }

                tx.Complete();

            }

    }

}

 

 

Working with search paths   工作与搜索路径

Npgsql可以让你修改搜索路径时,连接到一个数据库. 为了做到这一点,就说明它在你的连接字符串与句法:searchpath = 'blablabla,blabla,blabla '. 注意到指定的搜索路径连接字符串,您可能希望添加公共的架构是不会自动添加.

Working with Arrays 

In orderto use Npgsql array support, you may specify your parameter dbtype as an OR'edoperation. Anything that implements IEnumerable<T> where T is a typealready supported by npgsql will be treated the same as T[], anything thatimplements IEnumerable<U> where U implements IEnumerable<T> will betreated the same as T[,] (but cause an error if it's a "jagged"array, as postgres doesn't support them) and so on. For example,List<ICollection<short>> will be treated as a 2-dimensional arrayof 16bit-integers. For example, to use an array of Int32 you will use somethinglike that:

command.Parameters.Add(newNpgsqlParameter("arrayParam", NpgsqlDbType.Array |NpgsqlDbType.Int32));

 

Or youcan specify directly the value of parameter to be an array:

 

Int32 a = new Int32[2];

 

a[0] = 4;

a[1] = 2;

 

command.Parameters.Add(newNpgsqlParameter("@parameter")).Value = a;

 

Here isa complete example:

using System;

using System.Data;

using Npgsql;

using NpgsqlTypes;

 

public class c

{

        public static void Main(String[] args)

        {

                //NpgsqlEventLog.Level =LogLevel.Debug;

                //NpgsqlEventLog.LogName ="NpgsqlTests.LogFile";

                //NpgsqlEventLog.EchoMessages =true;

 

                NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Userid=npgsql_tests;password=npgsql_tests;");

                conn.Open();

 

                NpgsqlCommand d = newNpgsqlCommand();

 

                Int32[] a = new Int32[2];

 

                a[0] = 4;

                a[1] = 2;

 

                NpgsqlCommand command = newNpgsqlCommand("select :arrayParam", conn);

                command.Parameters.Add(newNpgsqlParameter("arrayParam", NpgsqlDbType.Array |NpgsqlDbType.Integer));

                command.Parameters[0].Value =a;

                Console.WriteLine(command.ExecuteScalar());

                conn.Close();

        }

}

 

This iswhat postgresql logs:

LOG:  connection received: host=127.0.0.1port=37356

DEBUG:  forked new backend, pid=10616 socket=6

LOG:  connection authorized: user=npgsql_testsdatabase=npgsql_tests

LOG:  statement: SELECT oid, typname FROM pg_typeWHERE typname IN ('oidvector', '_oidvector', 'unknown', '_unknown','refcursor', '_refcursor', 'char', '_char', 'bpchar', '_bpchar', 'varchar','_varchar', 'text', '_text', 'name', '_name', 'bytea', '_bytea', 'bit', '_bit','bool', '_bool', 'int2', '_int2', 'int4', '_int4', 'int8', '_int8', 'oid','_oid', 'float4', '_float4', 'float8', '_float8', 'numeric', '_numeric','inet', '_inet', 'money', '_money', 'date', '_date', 'time', '_time', 'timetz','_timetz', 'timestamp', '_timestamp', 'timestamptz', '_timestamptz', 'point','_point', 'lseg', '_lseg', 'path', '_path', 'box', '_box', 'circle', '_circle','polygon', '_polygon', 'uuid', '_uuid', 'xml', '_xml')

 

LOG:  statement: select array['4','2']::int4[]

 

LOG:  disconnection: session time: 0:00:00.342user=npgsql_tests database=npgsql_tests host=127.0.0.1 port=37356

DEBUG:  server process (PID 10616) exited with exitcode 0

 

And thisis what Npgsql shows in console:

System.Int32[]

 

3.1 Using Npgsql Logging support   使用npgsql记录支持

有时是必要的跟踪npgsql的行为,错误日志消息。npgsql可以到指定的文件或显示到控制台.

有三个级别日志记录的::

_       None

_       Normal

_       Debug

以下NpgsqlEventLog静态属性也可以被指定:

_       Level - Can be one of the LogLevel enum values: None, Normal, Debug.

_       LogName - Full path of the file where to log into.

_       EchoMessages - Log to the console.

下面的例子就是向你展示了如何记录数据和文件使用控制台水平”调试":

using System.Data;

using Npgsql;

 

public staticclass NpgsqlUserManual

{

  public static void Main(String[] args)

  {

    // Enable logging.

    NpgsqlEventLog.Level = LogLevel.Debug;

    NpgsqlEventLog.LogName ="NpgsqlTests.LogFile";

    NpgsqlEventLog.EchoMessages = true;

 

    NpgsqlConnection conn = newNpgsqlConnection("Server=127.0.0.1;Port=5432;UserId=joe;Password=secret;Database=joedata;");

   conn.Open();

    conn.Close();

  }

}

 

运行该代码给下列输出:

SetNpgsqlEventLog.EchoMessages = True

EnteringNpgsqlConnection.NpgsqlConnection()

EnteringNpgsqlConnection.ParseConnectionString()

Connection stringoption: DATABASE = joedata

Connection stringoption: SERVER = 127.0.0.1

Connection stringoption: USER ID = joe

Connection stringoption: PASSWORD = secret

EnteringNpgsqlConnection.Open()

Connected to:127.0.0.1:5432

EnteringNpgsqlConnection.WritestartupPacket()

EnteringNpgsqlStartupPacket.NpgsqlStartupPacket()

EnteringNpgsqlStartupPacket.WriteToStream()

EnteringPGUtil.WriteLimString()

EnteringPGUtil.WriteLimString()

EnteringPGUtil.WriteLimString()

EnteringPGUtil.WriteLimString()

EnteringPGUtil.WriteLimString()

EnteringNpgsqlConnection.HandleStartupPacketResponse()

AuthenticationRequestmessage from Server

Server requestedcleartext password authentication.

EnteringNpgsqlPasswordPacket.NpgsqlPasswordPacket()

EnteringNpgsqlPasswordPacket.WriteToStream()

EnteringPGUtil.WriteString()

Listening for nextmessage

AuthenticationRequestmessage from Server

Listening for nextmessage

BackendKeyDatamessage from Server

EnteringNpgsqlBackEndKeyData.ReadFromStream()

Got ProcessID.Value: 3116

Got SecretKey.Value: -132883070

Listening for nextmessage

ReadyForQuerymessage from Server

Listening for nextmessage

Connectioncompleted

EnteringNpgsqlConnection.Close()

 

我用“调试”来说明大量的信息可以。当然,“正常”的水平太冗长。这个数据写入(文件npgsqltests。logfile。)

3.2 Npgsql design time support - VS.Net support   npgsql设计时支持-vs.net

  Npgsql 0.6至高提供初始设计时间的支持。这意味着你可以拖放一个NpgsqlConnection在。net可视化工作室设计的形式(就像与SqlConnections或OleDbConnections)。

此外,一个对话框可轻易编辑和验证ConnectionString

你必须这样做:

1.    安装Npgsql.dll进入GAC

2.    添加一个新的Registry-Key HKEY_LOCAL_MACHINE  \SOFTWARE\Microsoft\.NETFramework\AssemblyFolders'它的默认值和Npgsql.dll一样。

3.    打开Visual Studio .NET

4.    右击“数据”选项卡在工具箱

5.    单击 "Add/Remove Element"

6.    在。net”选项卡,选择NpgsqlConnection

对。2005年,你必须“网上添加注册关键HKEY_LOCAL_MACHINE \软件\ Microsoft下.NETFramework \ v2.0.50727 \AssemblyFoldersEx’与任何你喜欢的名字叫我(p ostgresql的)目录的默认值(落后于反斜杠)在大会之所在。谢谢爱德华diener给小费。

“你会有一个图标名叫npgsqlconnection在“数据”选项卡上的工具箱。

3.3 ConnectionPool considerations   ConnectionPool考量

Npgsql会清除所有的连接池中从没有任何问题,只要有联系。这将允许容易失稳问题,从任何的复苏可能发生。尽管这种策略可能不会得到最好的性能,它将保证池仍然保持一致时,问题就会出现。两种方法来清理水池可通过NpgsqlConnection:ClearPool和ClearAllPools。你可以使用它们来清理池手动操作.

3.4 Using Npgsql with ProviderFactory   使用Npgsql与ProviderFactory

Npgsql可用于与供应商工厂模式,让你写的代码是独立的数据库。

为了做到这一点,你必须使用下列配置:

<?xmlversion="1.0" encoding="iso-8859-1" ?>

<configuration>

 

<system.data>

<DbProviderFactories>

 

<addname="Npgsql Data Provider" invariant="Npgsql"support="FF" description=".Net Framework Data Provider forPostgresql Server" type="Npgsql.NpgsqlFactory, Npgsql, Version=2.0.1.0,Culture=neutral, PublicKeyToken=5d8b90d52f46fda7"/>

 

</DbProviderFactories>

</system.data>

 

</configuration>

 

Thisconfiguration can be put inside the global machine.config file or in theapplication specific .config file.

Afterthat, you can write code like the following:

 

using System;

using System.Data;

usingSystem.Data.Common;

 

public class c

{

    public static void Main(String[] args)

    {

       DbProviderFactory factory =DbProviderFactories.GetFactory("Npgsql");

       DbConnection conn =factory.CreateConnection();

       conn.ConnectionString ="Server=127.0.0.1;User id=npgsql_tests;password=npgsql_tests;";

       conn.Open();

       conn.Close();

    }

}

 

4. Current Npgsql Status   目前Npgsql状态

Supported data types      支持数据类型

Npgsqlsupports the following data types:

Postgresql Type

NpgsqlDbType

System.DbType Enum

.Net System Type

int8

Bigint

Int64

Int64

bool

Boolean

Boolean

Boolean

Box, Circle, Line, LSeg, Path, Point, Polygon

Box, Circle, Line, LSeg, Path, Point, Polygon

Object

Object

bytea

Bytea

Binary

Byte[]

date

Date

Date

DateTime, NpgsqlDate

float8

Double

Double

Double

int4

Integer

Int32

Int32

money

Money

Decimal

Decimal

numeric

Numeric

Decimal

Decimal

float4

Real

Single

Single

int2

Smallint

Int16

Int16

text

Text

String

String

time

Time

Time

DateTime, NpgsqlTime

timetz

Time

Time

DateTime, NpgsqlTimeTZ

timestamp

Timestamp

DateTime

DateTime, NpgsqlTimestamp

timestamptz

TimestampTZ

DateTime

DateTime, NpgsqlTimestampTZ

interval

Interval

Object

TimeSpan, NpgsqlInterval

varchar

Varchar

String

String

inet

Inet

Object

NpgsqlInet, IPAddress

(there is an implicity cast operator to convert NpgsqlInet objects into IPAddress if you need to use IPAddress and have only NpgsqlInet)

bit

Bit

Boolean

Boolean, Int32

(If you use an Int32 value, odd values will be translated to bit 1 and even values to bit 0)

uuid

Uuid

Guid

Guid

array

Array

Object

Array

In order to explicitly use array type, specify NpgsqlDbType as an 'OR'ed type: NpgsqlDbType.Array | NpgsqlDbType.Integer for an array of Int32 for example.

Features   特点

_       You can send select, insert, delete queries  您可以发送选择、插入、删除查询

_       You can call functions  你可以调用呼叫函数

_       You can get resultset from functions  你能产生函数

_       You can use parameters in your queries. Input, Output and InputOuputparameters are supported   你可以使用参数在你的问题里。输入、输出、InputOuput参数的支持

_       Parameter names have ":" markers or "@" markers toeasy migration of code. :parameter -or- @parameter   参数名字:“标记”或“@”标记的代码更容易迁移或者- @parameter。参数

_       Support for transactions    支持交易

 

 

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值