使用Powershell连接到远程PostgreSql数据库

sti*_*ing 5 postgresql powershell odbc

我正在尝试使用Powershell连接到远程PostgreSql数据库。这是我第一次使用Powershell,所以如果这是一个菜鸟问题,我感到抱歉。这是我的代码:

$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();
Run Code Online (Sandbox Code Playgroud)

运行此命令时,出现“异常调用“ Open”,参数为“ 0”:错误[IM002] [Microsoft] [ODBC驱动程序管理器]找不到数据源名称,未指定默认驱动程序“。我已经下载并安装了pgsqlodbc驱动程序,但是仍然出现此错误。有谁知道我该如何解决?我已经搜索了互联网,但现在我真的什么也没找到。

谢谢。

小智 8

查阅: https: //odbc.postgresql.org/
下载:https://www.postgresql.org/ftp/odbc/versions/msi/

Windows 上的数据源 (ODBC):开始 → 搜索 → odbc → 用户 DSN → 添加/配置

ODBC 驱动程序设置屏幕截图

例子 :

$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();
Run Code Online (Sandbox Code Playgroud)


dog*_*dog 8

如果你的客户端安装了 postgresql,你可以使用 postgresql 自带的 psql

$dburl="postgresql://exusername:expw@exhostname:5432/postgres"
$data="select * from extable" | psql --csv $dburl | ConvertFrom-Csv
Run Code Online (Sandbox Code Playgroud)

您的路径中必须有 psql 或引用它,例如 C:\Program Files\PostgreSQL\12\bin。应该能够输入“psql”并在 powershell 中查看输出。


CB.*_*CB. 3

检查 ODBC 数据源中是否存在 DSN。如果没有,您必须创建一个进入“控制面板”、“管理”。工具”、“数据源 (ODBC)”。然后选择“添加用户 DSN”- 选择 PostgreSQL 驱动程序,并填写您的服务器和数据库详细信息。测试连接检查是否一切正常!