使用Powershell从PostgreSQL中检索数据

时间:2015-04-28 21:58:15

标签: 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)

4 个答案:

答案 0 :(得分:2)

尝试一下
用$ cnString
中的数据库名称替换“#database#” 用$ cnString
中的服务器IP地址替换“#server_ip#” 用$ cnString和$ user
中的有效用户替换“#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();

答案 1 :(得分:2)

通过psql(与postgresql一起提供)

fun getTimess(time: Array<Int>, direction: Array<Int>): Array<Int> {

    //check for range of values
    if (time.size > 100_000 || direction.size > 100_000) return emptyArray()

    //ensure that direction values are between 0 and 1
    if (direction.max() !in (0..1) || direction.min() !in (0..1)) return emptyArray()

    val result = Array(time.size) { 0 }
    val endTime: Int = time.max() ?: 0

    //check for time range
    if (endTime > 1_000_000_000 || endTime < 0) return emptyArray()


    if (endTime == 0) return result
    val inQueue: Queue<Pair<Int, Int>> = LinkedList()
    val outQueue: Queue<Pair<Int, Int>> = LinkedList()

    var currentTime = 0 //current time

    //indicates who used the turnstile in the previous second,
    // -1 if non used the turnstile in the last sec.
    var turnstile = -1

    for (i in time.indices) {
        if (direction[i] == 1) {
            outQueue.add(Pair(time[i], i))
        } else {
            inQueue.add(Pair(time[i], i))
        }
    }

    while (outQueue.isNotEmpty() || inQueue.isNotEmpty()) {
        //checking fot exit
        if (outQueue.isNotEmpty()
            && outQueue.peek().first <= currentTime
            && (turnstile == 1 || turnstile == -1 || inQueue.isEmpty()
                    || (inQueue.peek().first > currentTime && turnstile == 0))
        ) {
            result[outQueue.poll().second] = currentTime
            turnstile = 1

        } else if (inQueue.isNotEmpty() && inQueue.peek().first <= currentTime) {
            result[inQueue.poll().second] = currentTime
            turnstile = 0
        } else {
            turnstile = -1
        }

        currentTime++
    }

    return result
}

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

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

如果您想重新输入类型信息,可以执行以下操作:

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

答案 2 :(得分:0)

我对@dog的处理方式略有不同,我无法使--csv正常工作,因此只能使用元组返回返回的行,然后将其解析为类列表(碰巧称为OnlineCourses):< / p>

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)
}

答案 3 :(得分:0)

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

$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)
}