Accessing Postgresql from .NET using the Npgsql provider
One of the more popular .NET providers for Postgresql is Npgsql, which is ADO.NET compatible and is used nearly identically as other .NET database providers.
A typical query is performed by creating a command, binding parameters, and then executing the command. In C#:
var connString = "Host=myserv;Username=myuser;Password=mypass;Database=mydb";
using (var conn = new NpgsqlConnection(connString))
{
var querystring = "INSERT INTO data (some_field) VALUES (@content)";
conn.Open();
// Create a new command with CommandText and Connection constructor
using (var cmd = new NpgsqlCommand(querystring, conn))
{
// Add a parameter and set its type with the NpgsqlDbType enum
var contentString = "Hello World!";
cmd.Parameters.Add("@content", NpgsqlDbType.Text).Value = contentString;
// Execute a query that returns no results
cmd.ExecuteNonQuery();
/* It is possible to reuse a command object and open connection instead of creating new ones */
// Create a new query and set its parameters
int keyId = 101;
cmd.CommandText = "SELECT primary_key, some_field FROM data WHERE primary_key = @keyId";
cmd.Parameters.Clear();
cmd.Parameters.Add("@keyId", NpgsqlDbType.Integer).Value = keyId;
// Execute the command and read through the rows one by one
using (NpgsqlDataReader reader = cmd.ExecuteReader())
{
while (reader.Read()) // Returns false for 0 rows, or after reading the last row of the results
{
// read an integer value
int primaryKey = reader.GetInt32(0);
// or
primaryKey = Convert.ToInt32(reader["primary_key"]);
// read a text value
string someFieldText = reader["some_field"].ToString();
}
}
}
} // the C# 'using' directive calls conn.Close() and conn.Dispose() for us
Accessing PostgreSQL with the C-API
The C-API is the most powerful way to access PostgreSQL and it is surprisingly comfortable.
Compilation and linking
During compilation, you have to add the PostgreSQL include directory, which can be found with pg_config --includedir
, to the include path.
You must link with the PostgreSQL client shared library (libpq.so
on UNIX, libpq.dll
on Windows). This library is in the PostgreSQL library directory, which can be found with pg_config --libdir
.
Note: For historical reason, the library is called libpq.so
and not libpg.so
, which is a popular trap for beginners.
Given that the below code sample is in file pgquery.c
, compilation and linking would be done with
gcc -Wall -I "$(pg_config --includedir)" -L "$(pg_config --libdir)" -o pgquery pgquery.c -lpq
with the GNU C compiler (consider adding -Wl,-rpath,"$(pg_config --libdir)"
to add the library search path) or with
cl /MT /W4 /I <include directory> pgquery.c <path to libpq.lib>
on Windows with Microsoft Visual C.
Sample program
/* necessary for all PostgreSQL client programs, should be first */
#include <libpq-fe.h>
#include <stdio.h>
#include <string.h>
#ifdef TRACE
#define TRACEFILE "trace.out"
#endif
int main(int argc, char **argv) {
#ifdef TRACE
FILE *trc;
#endif
PGconn *conn;
PGresult *res;
/* parameter type should be guessed by PostgreSQL */
const Oid paramTypes[1] = { 0 };
/* parameter value */
const char * const paramValues[1] = { "tables" };
/* format options for PQprint */
PQprintOpt printOpt = {
1, /* print headers */
1, /* align columns */
0, /* not old format */
0, /* no HTML */
0, /* no expanded format */
0, /* don't use pager */
"|", /* field deparator */
NULL, /* HTML attributes */
NULL, /* HTML table caption */
NULL /* no replacement field names */
};
/*
* Using an empty connectstring will use default values for everything.
* If set, the environment variables PGHOST, PGDATABASE, PGPORT and
* PGUSER will be used.
*/
conn = PQconnectdb("");
/*
* This can only happen if there is not enough memory
* to allocate the PGconn structure.
*/
if (conn == NULL)
{
fprintf(stderr, "Out of memory connecting to PostgreSQL.\n");
return 1;
}
/* check if the connection attempt worked */
if (PQstatus(conn) != CONNECTION_OK)
{
fprintf(stderr, "%s\n", PQerrorMessage(conn));
/*
* Even if the connection failed, the PGconn structure has been
* allocated and must be freed.
*/
PQfinish(conn);
return 1;
}
#ifdef TRACE
if (NULL == (trc = fopen(TRACEFILE, "w")))
{
fprintf(stderr, "Error opening trace file \"%s\"!\n", TRACEFILE);
PQfinish(conn);
return 1;
}
/* tracing for client-server communication */
PQtrace(conn, trc);
#endif
/* this program expects the database to return data in UTF-8 */
PQsetClientEncoding(conn, "UTF8");
/* perform a query with parameters */
res = PQexecParams(
conn,
"SELECT column_name, data_type "
"FROM information_schema.columns "
"WHERE table_name = $1",
1, /* one parameter */
paramTypes,
paramValues,
NULL, /* parameter lengths are not required for strings */
NULL, /* all parameters are in text format */
0 /* result shall be in text format */
);
/* out of memory or sever communication broken */
if (NULL == res)
{
fprintf(stderr, "%s\n", PQerrorMessage(conn));
PQfinish(conn);
#ifdef TRACE
fclose(trc);
#endif
return 1;
}
/* SQL statement should return results */
if (PGRES_TUPLES_OK != PQresultStatus(res))
{
fprintf(stderr, "%s\n", PQerrorMessage(conn));
PQfinish(conn);
#ifdef TRACE
fclose(trc);
#endif
return 1;
}
/* print formated result */
PQprint(stdout, res, &printOpt);
/* this must be done after every statement to avoid memory leaks */
PQclear(res);
/* close the database connection and release memory */
PQfinish(conn);
#ifdef TRACE
fclose(trc);
#endif
return 0;
}