【问题标题】:Retrieve data from PostgreSQL using Powershell使用 Powershell 从 PostgreSQL 检索数据
【发布时间】: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


【解决方案1】:

我对@dog 有一个稍微不同的方法,我无法让 --csv 工作,所以我只使用元组返回的行,然后将它们解析为一个类列表(恰好称为 OnlineCourses) :

class OnlineCourse
{
    [int]$id
    [string]$email
    [string]$courseName
    [int]$completedRatio
    [datetime]$lastActivity
    [String]$provider
    OnlineCourse([int]$id,
        [string]$email,
        [string]$courseName,
        [int]$completedPerc,
        [datetime]$lastActivity,
        [String]$provider) {
            $this.id = $id
            $this.email = $email.Trim()
            $this.courseName = $courseName.Trim()
            $this.completedRatio = $completedPerc
            $this.lastActivity = $lastActivity
            $this.provider = $provider.Trim()
    }
}

$connstr="postgresql://exusername:expw@exhostname:5432/postgres"
$data = "select * from onlinecourses" | .\psql -t $connstr

$list = New-Object Collections.Generic.List[OnlineCourse]

foreach ($field in $data) { 
    $id, $email, $courseName,  $completedratio, $lastactivity, $provider = $field.split('|')
    $course = [OnlineCourse]::new($id, $email, $courseName, $completedratio, $lastactivity, $provider)
    $list.Add($course)
}

【讨论】:

    【解决方案2】:

    使用点符号。您不需要拆分数据。

    $list = New-Object Collections.Generic.List[OnlineCourse]
    
    foreach($element in $results)
    {
        $tempObj= New-Object OnlineCourse($element.id,$element.courseName,$element.completedRatio,$element.completedRatio,$element.lastActivity, $element.provider)
        $list.add($tempObj)
    }
    

    【讨论】:

      【解决方案3】:

      通过 psql,postgresql 自带

      $dburl="postgresql://exusername:expw@exhostname:5432/postgres"
      $data="select * from extable" | psql --csv $dburl | ConvertFrom-Csv
      

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

      作为警告,请期待字符串。例如 $data[0].age.GetType() 将是字符串,尽管它以整数形式存储在数据库中。您可以立即转换它,稍后再转换它,或者希望 powershell 正确推断类型。

      如果你想添加回类型信息可以做例如:

      $data = $data | %{[pscustomobject]@{name=$_.name;age=[int]$_.age}}
      

      【讨论】:

      • 我今天试过了,我收到了错误psql.exe: illegal option -- csv 任何想法?
      • 我解决了$data = "select * from feeds" | .\psql $connstr | ConvertFrom-Csv
      【解决方案4】:

      试试这个
      将“#database#”替换为 $cnString
      中的数据库名称 将“#server_ip#”替换为 $cnString 中的服务器 IP 地址
      将“#user#”替换为 $cnString 和 $user
      中的有效用户 将“#pass#”替换为 $pass
      中的有效通行证 用您的数据库的有效表名替换“#table#”
      用您的数据库端口替换 5432

      
      $cnString = "DRIVER={PostgreSQL Unicode(x64)};DATABASE=#database#;SERVER=#server_ip#;PORT=5432;UID=#user#;"
      $user="#user#"
      $pass="#pass#"
      
      $conn = New-Object -comobject ADODB.Connection
      $conn.Open($cnString,$user,$pass)
      
      $recordset = $conn.Execute("SELECT * FROM #table# limit 1;")
      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();
      
      

      【讨论】:

        【解决方案5】:

        我最终弄明白了——这就是我所做的

        $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
        

        【讨论】:

        • 设置 ODBC 连接:从 odbc.postgresql.org 安装 postgreSQL ODBC 驱动程序 创建 ODBC 连接 Windows 7 中有两个 ODBC 管理器副本 您必须使用 C 中的 64 位版本: \Windows\SysWOW64 不要使用 system32 中的那个(它是管理工具菜单上的默认设置 - 不要使用它)
        猜你喜欢
        • 2012-03-23
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-02-19
        • 2010-09-25
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多