ken*_*ken 5 postgresql powershell select
我一直在努力解决从 Powershell 到 PostgreSQL 的数据库连接问题。我终于能够连接并插入到数据库中。现在我不知道如何从数据库选择中提取数据到变量中。
为了清楚起见,我不包括我的插入内容,但稍后会将其添加到此线程上,因为我知道它很难找到并且可能对某人有帮助。
所以这是我的代码:
# use existing 64 bit ODBC System DSN that we set up manually
$DBconn = New-Object -comobject ADODB.Connection
$DBconn.Open("PostgreSQL35W")
$theQuery = "select * from test1"
$theObject = $DBconn.Execute($theQuery) # $theObject is a System.__ComObject
$numRecords = $theObject.RecordCount
write-host "found $numRecords records" # getting -1
$theObject.MoveFirst() # throws no error
# $theValue = $theObject.DataMember # throws no error, but gives no result
$theValue = $theObject.Index[1] # throws "Cannot index into a null array"
write-host($theValue)
Run Code Online (Sandbox Code Playgroud)
通过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 中查看输出。
作为警告,请注意字符串。例如 $data[0].age.GetType() 将是字符串,尽管它作为整数存储在数据库中。您可以立即转换它,稍后转换它,或者希望 powershell 正确推断类型。
如果你想添加回类型信息可以这样做,例如:
$data = $data | %{[pscustomobject]@{name=$_.name;age=[int]$_.age}}
Run Code Online (Sandbox Code Playgroud)
我最终弄清楚了 - 这就是我所做的
$conn = New-Object -comobject ADODB.Connection
# use existing 64 bit ODBC System DSN that we set up manually
$conn.Open("PostgreSQL35W")
$recordset = $conn.Execute("SELECT * FROM JobHistory")
while ($recordset.EOF -ne $True)
{
foreach ($field in $recordset.Fields)
{
'{0,30} = {1,-30}' -f # this line sets up a nice pretty field format, but you don't really need it
$field.name, $field.value
}
'' # this line adds a line between records
$recordset.MoveNext()
}
$conn.Close();
Exit
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9888 次 |
| 最近记录: |