ODBC连接字符串格式问题

时间:2018-09-04 11:03:31

标签: postgresql powershell odbc connection-string

最近,我想在PowerShell中的$profile中创建一个函数,该函数连接到Postgres服务器并执行查询。 该函数看起来像这样:

function db{
    Param(
        [string]$provider = "PostgreSQL",
        [string]$type = "UNICODE",
        [string]$server = "localhost",
        [string]$port = "5432",
        [string]$db = "dbname",
        [string]$uid = "username",
        [string]$pwd = "password",
        [string]$q = ""
    )
    #future upgrade: read default parameters from file

    $DBConnectionString = 'Driver={'+$driver+' '+$type+'}:Server='+$server+';Port='+$port+';Database='+$db+';Uid='+$uid+';Pwd='+$pwd+';';
    $DBConn = New-Object System.Data.Odbc.OdbcConnection;
    $DBConn.ConnectionString = $DBConnectionString;
    Write-Output "this connectionstring: $DBConnectionString";
    $DBConn.Open();
    $DBCmd = $DBConn.CreateCommand();
    $DBCmd.CommandText = $q;
    $DBCmd.ExecuteReader();
    $DBConn.Close();
}

如您所见,我放置了一个Write-Output,以便可以看到连接字符串的值。

输出中给我的错误是:

Exception setting "ConnectionString": "Format of the initialization string
does not conform to specification starting at index 0."
At C:\Users\...\Microsoft.PowerShell_profile.ps1:84 char:1
+ $DBConn.ConnectionString = $DBConnectionString

Write-Output返回:

this connectionstring: Driver={PostgreSQL UNICODE}:Server=localhost;Port=5432;Database=dbname;Uid=username;Pwd=password;

因此$DBConnectionString变量中包含的值是正确的。

0 个答案:

没有答案