8

I'm looking for the best way to connect to a Heroku Postgres database from an outside application. The application is in asp.net. I am trying to use NpgSQL but am getting a certificate unknown error. Has anyone done that? Do you have any pointers?

2
  • Hi. Welcome to SO, what have you at least tried? Can you give us some starting code to help you? Commented May 17, 2016 at 12:58
  • Is PostgreSQL running SSL=on? Commented May 17, 2016 at 13:00

2 Answers 2

23

I use this to "translate" the DATABASE_URL to a connection string

var databaseUrl = Environment.GetEnvironmentVariable("DATABASE_URL");
var databaseUri = new Uri(databaseUrl);
var userInfo = databaseUri.UserInfo.Split(':');

var builder = new NpgsqlConnectionStringBuilder
{
    Host = databaseUri.Host,
    Port = databaseUri.Port,
    Username = userInfo[0],
    Password = userInfo[1],
    Database = databaseUri.LocalPath.TrimStart('/')
};

return builder.ToString();
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you very much for the answer it worked for me! I just want to add, I needed to add to connect from my local to heroku server. SslMode = SslMode.Require, TrustServerCertificate = true
11

I am using the following connection string to connect to Heroku Postgres Database:

string connString = "User ID=<user>;Password=<pass>;Host=<host>;Port=<port>;Database=<database>;Pooling=true;Use SSL Stream=True;SSL Mode=Require;TrustServerCertificate=True;"

where <user>, <pass>, <host>, <port> and <database> are values from heroku postgres app settings. Port is 5432 by default.

Then using NpgSql I create instance of NpgsqlConnection:

var conn = new NpgsqlConnection(connString);

Dafault sample: http://www.npgsql.org/doc/index.html

1 Comment

For those reading in the future I highly recommend you obtain the database URI programmatically by using Heroku's Platform API - you can curl to get the database URI you'll have to pass in your authentication token as a header. @Set 's solution will work but is liable to break under certain circumstances.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.