Powershell连接SQL数据库


先前的技巧中我们学习了如何创建一个SQL连接字符串,当你有了一个连接字符串并且它是有效的,接下来的例子就是演示如何向数据库提交一个SQL命令:

#requires -Version 2

# make sure this is a valid connection string to your database
# see www.connectionstrings.com for reference
$connectionString = 'Provider=SQLOLEDB.1;Password=.topSecret!;Persist Security 
 Info=True;User ID=sa;Initial Catalog=test;Data Source=myDBServer\SQLEXPRESS2012'

# make sure this is valid SQL for your database
# so in this case, make sure there is a table called "test"
$sql = 'select * from test'

$db = New-Object -ComObject ADODB.Connection
$db.Open($connectionString)
$rs = $db.Execute($sql)

$results = While ($rs.EOF -eq $false)
{
    $CustomObject = New-Object -TypeName PSObject
    $rs.Fields | ForEach-Object -Process {
        $CustomObject | Add-Member -MemberType NoteProperty -Name $_.Name -Value $_.Value
    }
    $CustomObject
    $rs.MoveNext()
}
$results | Out-GridView

原文地址:Accessing an SQL Database with a Connection String

本文链接: https://www.pstips.net/accessing-an-sql-database-with-a-connection-string.html
请尊重原作者和编辑的辛勤劳动,欢迎转载,并注明出处!

发表评论

您的电子邮箱地址不会被公开。 必填项已用 * 标注