Npgsql: User's Manual

Copyright © The Npgsql Development Team

Last update: 2002-07-05 18:00 by mcmicro

Category: External documentation

Intended Audience: Npgsql Users

1. What is Npgsql?

Npgsql is a .Net Data Provider for Postgresql Database Server.

It allows a .Net client application (Console, WinForms, ASP.NET, Web Services...) to use a PostgreSQL server to send and receive data. It is developed using the guidelines specified in the .Net docs.

2. Npgsql Usage

This section explains Npgsql usage in a .Net Application. If you are used to developing Data Access applications using the Sql Server, OleDB or ODBC.NET providers, using Npgsql is very similar.

Note: Npgsql is still under development. Only features currently supported will be demonstrated. As Npgsql matures, more functionality will be available to be used.

First, to use Npgsql objects more easily, you have to tell the compiler to use the Npgsql namespace. It will also be needed to use the System.Data namespace as a lot of classes used for data manipulation reside in it. To do that, in C#, you use the using directive:

using System.Data;
using Npgsql;

For example, to establish a connection to a server located at ip 172.16.0.1, port 5432, as the user joe, with the password secret, using the database joedata, you use the NpgsqlConnection as:

using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    NpgsqlConnection conn = new NpgsqlConnection("Server=172.16.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();
    conn.Close();
  }
}

This source doesn't do anything useful. It only connects to the database and disconnects. If there is an error, a NpgsqlException is thrown. Now, suppose there is a table called table1 with two fields a and b both of type int. If you want to add the tuple (1, 1) in this table you could send the insert statement as follows:

using System;
using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    NpgsqlConnection conn = new NpgsqlConnection("Server=172.16.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();
    
    NpgsqlCommand command = new NpgsqlCommand("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();
    }
  }
}

To execute statements which return just one value you use the ExecuteScalar() method of the Command object:

using System;
using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    NpgsqlConnection conn = new NpgsqlConnection("Server=172.16.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();
    
    NpgsqlCommand command = new NpgsqlCommand("select version()", conn);
    String serverversion;
    
    try
    {
      serverversion = (String)command.ExecuteScalar();
    }
    
    Console.WriteLine("PostgreSQL server version: {0}", serverversion);
    
    finally
    {
      conn.Close();
    }
  }
}
Other queries could also be used, for example "select count(*) from table1". Also, queries that don't return single values could be used, but only the first column of the first row would be returned.

2.1 Npgsql.dll file location

In order for the .Net Runtime to locate the Npgsql.dll library, this file must be put in the same directory the application is, unless you specify another directory as a path to private components through a configuration file (using the probing element). Please, see the .Net docs for information on how the runtime probes (locates) assemblies to be loaded. There is also a section called "Path to Private Components"

In ASP.NET and Web Services .Net Applications, there must be a directory called "bin" below the ASP.NET root application directory. So, for example the application directory is called "ASPNETApplication", Npgsql.dll must be placed in the "ASPNETApplication\bin" directory. If it's not, you will get a lot of compiling errors when trying to use Npgsql.

2.2 Using Npgsql Logging support

Sometimes it is necessary to trace Npgsql's behaviour to track errors. Npgsql can log messages to a specified file or to the console or both.

There are three levels of logging:

The following NpgsqlEventLog static properties may also be used:

The example below shows how to log to the console and a file using the level Debug:

using System.Data;
using Npgsql;

public static class NpgsqlUserManual
{
  public static void Main(String[] args)
  {
    // Enable logging.
    NpgsqlEventLog.Level = LogLevel.Debug;
    NpgsqlEventLog.LogName = "NpgsqlTests.LogFile";
    NpgsqlEventLog.EchoMessages = true;
	  
    NpgsqlConnection conn = new NpgsqlConnection("Server=172.16.0.1;Port=5432;User Id=joe;Password=secret;Database=joedata;");
    conn.Open();
    conn.Close();
  }
}

Running this code gives the following output:

Set NpgsqlEventLog.EchoMessages = True
Entering NpgsqlConnection.NpgsqlConnection()
Entering NpgsqlConnection.ParseConnectionString()
Connection string option: DATABASE = joedata
Connection string option: SERVER = 172.16.0.1
Connection string option: USER ID = joe
Connection string option: PASSWORD = secret
Entering NpgsqlConnection.Open()
Connected to: 172.16.0.1:5432
Entering NpgsqlConnection.WritestartupPacket()
Entering NpgsqlStartupPacket.NpgsqlStartupPacket()
Entering NpgsqlStartupPacket.WriteToStream()
Entering PGUtil.WriteLimString()
Entering PGUtil.WriteLimString()
Entering PGUtil.WriteLimString()
Entering PGUtil.WriteLimString()
Entering PGUtil.WriteLimString()
Entering NpgsqlConnection.HandleStartupPacketResponse()
AuthenticationRequest message from Server
Server requested cleartext password authentication.
Entering NpgsqlPasswordPacket.NpgsqlPasswordPacket()
Entering NpgsqlPasswordPacket.WriteToStream()
Entering PGUtil.WriteString()
Listening for next message
AuthenticationRequest message from Server
Listening for next message
BackendKeyData message from Server
Entering NpgsqlBackEndKeyData.ReadFromStream()
Got ProcessID. Value: 3116
Got SecretKey. Value: -132883070
Listening for next message
ReadyForQuery message from Server
Listening for next message
Connection completed
Entering NpgsqlConnection.Close()

I used the Debug level to show that a lot of information can be obtained. Of course, using the Normal level would be less verbose. Also, this same information was added to the file NpgsqlTests.LogFile.