Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Connect to remote PostgreSql database using Powershell

I'm trying to connect to a remote PostgreSql database using powershell. This is my first time using powershell so I'm sorry if this is a noob question. This is my Code:

$DBConnectionString = "Driver={PostgreSQL UNICODE}:Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = "SELECT * FROM mytable;";
$DBCmd.ExecuteReader();
$DBConn.Close();

When I run this I get "Exception Calling "Open" with "0" argument(s): ERROR [IM002] [Microsoft][ODBC Driver Manager] Data source name not found and no default driver specified". I've downloaded and installed the pgsqlodbc driver but I'm still getting this error. Does anyone have any ideas how I could fix this? I have searched the internet and I'm really not getting anywhere at this point.

Thanks.

like image 897
stirling Avatar asked Feb 09 '12 19:02

stirling


2 Answers

Consult: https://odbc.postgresql.org/
Download: https://www.postgresql.org/ftp/odbc/versions/msi/

Data sources (ODBC) on Windows: Start → Search → odbc → User DSN → Add/Configure

Screenshot ODBC Driver Setup

Example :

$MyServer = "<ip>"
$MyPort  = "5432"
$MyDB = "<database>"
$MyUid = "<user>"
$MyPass = "<pass>"

$DBConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=$MyServer;Port=$MyPort;Database=$MyDB;Uid=$MyUid;Pwd=$MyPass;"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = "SELECT * FROM tb_module;";
$DBCmd.ExecuteReader();
$DBConn.Close();
like image 119
Thiago Back Avatar answered Nov 12 '22 11:11

Thiago Back


You can use psql which comes with postgresql if you happen to have postgresql installed on your client

$dburl="postgresql://exusername:expw@exhostname:5432/postgres"
$data="select * from extable" | psql --csv $dburl | ConvertFrom-Csv

You must have psql in your path or reference it, its within e.g. C:\Program Files\PostgreSQL\12\bin. Should be able to type "psql" and see output within powershell.

like image 5
dog Avatar answered Nov 12 '22 09:11

dog