• 博客园logo
  • 会员
  • 众包
  • 新闻
  • 博问
  • 闪存
  • 赞助商
  • HarmonyOS
  • Chat2DB
    • 搜索
      所有博客
    • 搜索
      当前博客
  • 写随笔 我的博客 短消息 简洁模式
    用户头像
    我的博客 我的园子 账号设置 会员中心 简洁模式 ... 退出登录
    注册 登录
机灵小不懂
博客园    首页    新随笔    联系   管理    订阅  订阅

PowerShell 连接SQL

因为对SQL操作比较多,但有些操作其实都是重复性的,只是参数不太一样了,例如silo id, server name 等。希望可以通过powershell脚本提高效率。

尝试如下

1. 使用PowerShell 连接数据库,本地尝试,来至:http://www.pstips.net/getting-sql-server-connection-string.html.

当你用Powershell获取SQL连接字符串,你会需要“连接字符串”,这段字符串要包涵连接数据库实例的多个片段。

传统方法构建一个这样的字符串也不容易,下面有段函数也许可以帮助您完成:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#requires -Version 2
function Get-ConnectionString
{
    $Path = Join-Path -Path $env:TEMP -ChildPath 'dummy.udl'
   
    $null = New-Item -Path $Path -ItemType File -Force
   
    $CommandArg = """$env:CommonProgramFiles\System\OLE DB\oledb32.dll"",OpenDSLFile "  + $Path
 
    Start-Process -FilePath Rundll32.exe -ArgumentList $CommandArg -Wait
    $ConnectionString = Get-Content -Path $Path | Select-Object -Last 1
    $ConnectionString | clip.exe
    Write-Warning -Message 'Connection String is also available from clipboard'
    $ConnectionString
}

当你运行Get-ConnectionString,Powershell会弹出一个对话框,你可以提交一个测试连接,接着关闭窗口,Powershell将返回一个一个连接字符串。

使用如下配置连接成功。

 

 2. Powershell 连接SQL数据库,来至:http://www.pstips.net/accessing-an-sql-database-with-a-connection-string.html

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#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
posted @ 2016-08-26 11:20  机灵小不懂  阅读(1712)  评论(0)    收藏  举报
刷新页面返回顶部
博客园  ©  2004-2025
浙公网安备 33010602011771号 浙ICP备2021040463号-3