【发布时间】:2015-07-07 23:15:12
【问题描述】:
我一直在努力解决从 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)
【问题讨论】:
-
好吧,我最终解决了问题 - 这就是我所做的:
-
'code'$conn = New-Object -comobject ADODB.Connection # 使用我们手动设置的现有 64 位 ODBC 系统 DSN $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 设置了一个漂亮的字段格式,但你并不需要它 $field.name, $field.value } '' # 这行在记录之间添加了一行 $recordset.MoveNext() } $conn.Close() ;退出
标签: postgresql powershell select