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.
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
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();
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.
Check if the DSN exists in ODBC data source. If not you have to create one going to 'Control Panel', 'Admin. Tools', 'Data Sources (ODBC)'. Then select 'Add User DSN'-
Select the PostgreSQL driver, and fill in your server and database details.
Test connection to check is all ok!
You actually have a typo in your connection string after Driver declaration.
There is a double colon instead of a semicolon :)
Wrong:
{PostgreSQL UNICODE} : Server
Correct:
{PostgreSQL UNICODE} ; Server
I found the problem, I thought the Postgresql ODBC driver was installed, but it wasn't. I finally got it to work after finding this site: http://code.google.com/p/visionmap/wiki/psqlODBC Then I followed the instructions above. it works.
Thanks for all the help.
Related
I'm new to PowerShell. I'm able to establish connection to my PostgreSQL server and perform operation of deleting data from existing table. What I'm not able to perform is the copy statement. Below is my code.
$DBConnectionString = "Driver={PostgreSQL UNICODE(x64)};Server=mysvr;Port=5420;Database=mydb;Uid=myuser;Pwd=mypwd;Options='autocommit=off';"
$DBConn = New-Object System.Data.Odbc.OdbcConnection;
$DBConn.ConnectionString = $DBConnectionString;
$DBConn.Open();
$DeleteexistingdataDml3 = "delete from table1;delete from table2;"
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = $DeleteexistingdataDml3;
$DBCmd.ExecuteReader();
I'm getting error while performing the copy statement.
$Copydatatotable = "\copy table1 FROM '\\filedolder\table1data.csv' DELIMITER AS '|' CSV NULL AS '';
\copy table2 FROM '\\filedolder\table2data.csv' DELIMITER AS '|' CSV NULL AS '';"
$DBCmd = $DBConn.CreateCommand();
$DBCmd.CommandText = $Copydatatotable;
$DBCmd.ExecuteReader();
Error:
Exception calling "ExecuteReader" with "0" argument(s): "ERROR [42601] ERROR: syntax error at or near "";
Thank you.
My understanding is that \COPY is a client command. I expect that means that it's understood by psql only. A generic ODBC provider won't understand it.
If you use the Npgsql .Net client, you may be able to use the PosgresSQL COPY command with it, but the \COPY command is for the PostgreSQL client psql only.
If you must use the ODBC connection, your best bet is likely to build an INSERT command with parameters and inserting each row of your CSV file one row at a time. In general, that would look similar to this answer inside a loop, but using Powershell instead of C#, of course.
I currently use the following code to connect to a database in my Perl script:
my $dsn = 'dbi:ODBC:MYDATABASE';
my $database = 'uat_env';
my $user = 'user';
my $auth = 'password';
my $dbh = DBI->connect($dsn, $user, $auth, {
RaiseError => 1,
AutoCommit => 1
}) or die("Couldn't connect to database");
$dbh->do('use '.$database);
Now the port has changed from 1433 to 40450.
I am having trouble changing the port in the DSN. I thought this change would work but I am receiving a "DSN not found" error:
my $dsn = 'dbi:ODBC:MYDATABASE;Port=40450';
Any idea why this isn't working?
There are two formats for a DBI data source string for ODBC. You can say either
dbi:ODBC:DSN=MYDATABASE
or you can abbreviate that to
dbi:ODBC:MYDATABASE
which is what you have. If you use just the DSN then you can't add any more parameters, so your dbi:ODBC:MYDATABASE;Port=40450 is looking for DSN MYDATABASE;Port=40450 which clearly doesn't exist
The proper way to do this is to set up a new DSN which has a copy of all the parameters of MYDATABASE, but with a different port name
At a guess, I would say you may be able to write
dbi:ODBC:DSN=MYDATABASE;Port=40450
but I can't be sure and I have no way of testing
If your requirements are simple then you can supply all of the parameters instead of a DSN, like this
dbi:ODBC:Driver={SQL Server};Server=11.22.33.44;Port=40450
but you will have to supply the correct driver if you aren't using a SQL Server ODBC connection, and other parameters may be necessary
You should start by examining the values in the MYDATABASE DSN and go from there
I have a problem with connection from VisualBasic (Excel) to postgresql.
I define my connection like that:
Set ObjMyConn = New ADODB.Connection
ObjMyConn.ConnectionString = "Driver={PostgreSQL Unicode};Server=ip;Port=port;Database=db_name;Uid=user;Pwd=pass;"
ObjMyConn.Open
When I want to load 443532 rows into Excel with
Set objMyCmd = New ADODB.Command
Set objMyCmd.ActiveConnection = ObjMyConn
objMyCmd.CommandText = "select * from table"
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
It keeps showing me run-time error Out of memory error while reading tuples.
I have already upgraded my ODBC driver to the latest version. I read here that I have to set Use declare/catch to true somewhere (odbc driver I guess).
Is it possible to set it in VB code?
I believe you can just add the UseDeclareFetch=1option to the connection string like this:
"Driver={PostgreSQL Unicode};Server=ip;Port=port;Database=db_name;Uid=user;Pwd=pass;UseDeclareFetch=1"
But, if that doesn't work, there's another method - if you have set up a ODBC system data source with the ODBC Database Connection Administrator you can modify the registry key directly (provided you have the sufficient permissions).
The key you want to change is located under HKEY_LOCAL_MACHINE\SOFTWARE\ODBC\ODBC.INI\PostgreSQL35Wif you're using a System DSN and the following vba code will enable Use Declare/Fetch:
Const HKEY_CURRENT_USER = &H80000001
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set oReg=GetObject("winmgmts:{impersonationLevel=impersonate}!\\" &_
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\ODBC\ODBC.INI\PostgreSQL35W"
strValueName = "UseDeclareFetch"
strStringValues = "1"
oReg.SetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strStringValues
I'm following this tutorial.
When I run php scripts/load.mysql.php it says:
SQLSTATE[42000] [1102] Incorrect database name '/home/tirengarfio/workspace/ZendFW/gaziende/application/../data/db/guestbook-dev.db'
So I just tried to change the line
resources.db.params.dbname = APPLICATION_PATH "/../data/db/guestbook-dev.db"
to
resources.db.params.dbname = "guestbook-dev" and created a new database called guestbook.
but I get another error about the "guestbook" is not a file, exactly:
PHP Warning: file_get_contents(/home/tirengarfio/workspace/ZendFW/gaziende/scripts/data.mysql.sql): failed to open stream: No such file or directory in /home/tirengarfio/workspace/ZendFW/gaziende/scripts/load.mysql.php on line 81
This is the code around the line 81 error (checkout what var_dump() returns):
// Check to see if we have a database file already
$options = $bootstrap->getOption('resources');
$dbFile = $options['db']['params']['dbname'];
if (file_exists($dbFile)) {
unlink($dbFile);
}
// this block executes the actual statements that were loaded from
// the schema file.
try {
$schemaSql = file_get_contents(dirname(__FILE__) . '/schema.mysql.sql');
// use the connection directly to load sql in batches
$dbAdapter->getConnection()->exec($schemaSql);
var_dump($dbFile);die(); // this returns "guestbook-dev"
chmod($dbFile, 0666);
So.. how should I set the name for the database connection exactly?
Note: the example of the tutorial is for Sqlite and I'm trying to use MySQL. Is that point? I never used Sqlite.
Regards
here are the basic application.ini settings for a Mysql db,
resources.db.adapter = "pdo_Mysql"
resources.db.params.username = "username"
resources.db.params.password = "password"
resources.db.params.dbname = "database name"
resources.db.params.charset = "utf8"
resources.db.isDefaultTableAdapter = true //optional but very helpful if you only have one db
Mysql Needs a little more info then SqlLite.
As far as populating the DB for this Tutorial I just took the easy way and copied the SQL into phpmyadmin.
Note:
If you've never used SqlLite before, this might be great chance to learn something new. This tutorial really doesn't need Mysql. :)
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.
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
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();
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.
Check if the DSN exists in ODBC data source. If not you have to create one going to 'Control Panel', 'Admin. Tools', 'Data Sources (ODBC)'. Then select 'Add User DSN'-
Select the PostgreSQL driver, and fill in your server and database details.
Test connection to check is all ok!
You actually have a typo in your connection string after Driver declaration.
There is a double colon instead of a semicolon :)
Wrong:
{PostgreSQL UNICODE} : Server
Correct:
{PostgreSQL UNICODE} ; Server
I found the problem, I thought the Postgresql ODBC driver was installed, but it wasn't. I finally got it to work after finding this site: http://code.google.com/p/visionmap/wiki/psqlODBC Then I followed the instructions above. it works.
Thanks for all the help.