Try connecting Postgres SQL with .NET Core

Npgsql driver seems to be recompiled with .NET Core and this is a setup to prove that it works. This has been tested on Ubuntu 16.04 LTS with .NET Core 1.0.


.NET core should have been installed before trying following steps:


1. Setup a directory. Directory name used in this example is try-postgres.

mkdir try-postgres
cd try-postgres

2. Setup project using F# language.

dotnet new -l F#

3. Modify project.json to add Npgsql dependency. Add following line into the dependency block.

  "Npgsql": "3.*"

Version in package.json use * as wildcard (very Windows-oriented :). The final dependency block should look like this:

  "dependencies": {
    "Microsoft.FSharp.Core.netcore": "1.0.0-alpha-160509",
    "Npgsql": "3.*"

4. Try to connect PostgreSQL. Npgsql exposes its ADO classes via Npgsql namespace.

open System
open Npgsql

let CONNECTION_STRING = "Host=;Username=postgres;Password=blahblah;Database=test"

let main argv = 
  use connection = new NpgsqlConnection(CONNECTION_STRING)
  printfn "Opening connection!"
  printfn "Connected."
  use cmd = connection.CreateCommand()
  cmd.CommandText <- "SELECT * FROM person"

  use reader = cmd.ExecuteReader()
  while reader.Read() do
    printfn "Name: %s" <| reader.GetString(0)

  0 // return an integer exit code

5. Run the code to observe result.

dotnet run

That's it!