下面简单一个脚本实现访问sqlserver,支持所有版本的SQLserver。
你是否需要连接数据库?这里有一段代码演示如何查询和获取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
|
$Database = 'Name_Of_SQLDatabase' $Server = '192.168.100.200' $UserName = 'DatabaseUserName' $Password = 'SecretPassword' $SqlQuery = 'Select * FROM TestTable' # Accessing Data Base $SqlConnection = New-Object -TypeName System.Data.SqlClient.SqlConnection $SqlConnection .ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password" $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd .CommandText = $SqlQuery $SqlCmd .Connection = $SqlConnection $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter .SelectCommand = $SqlCmd $set = New-Object data.dataset # Filling Dataset $SqlAdapter .Fill( $set ) # Consuming Data $Path = "$env:temp\report.hta" $set .Tables[0] | ConvertTo-Html | Out-File -FilePath $Path Invoke-Item -Path $Path |
后来我又完善了这个代码,详细代码注释如下:
#配置信息 $Database = 'DemoDB' $Server = '"WIN-AHAU9NO5R6U\DOG"' $UserName = 'kk' $Password = '123456' #创建连接对象 $SqlConn = New-Object System.Data.SqlClient.SqlConnection #使用账号连接MSSQL $SqlConn.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;user id=$UserName;pwd=$Password" #或者以 windows 认证连接 MSSQL #$SqlConn.ConnectionString = "Data Source=$Server;Initial Catalog=$Database;Integrated Security=SSPI;" #打开数据库连接 $SqlConn.open() #执行语句方法一 $SqlCmd = New-Object System.Data.SqlClient.SqlCommand $SqlCmd.connection = $SqlConn $SqlCmd.commandtext = 'delete top(1) from dbo.B' $SqlCmd.executenonquery() #执行语句方法二 $SqlCmd = $SqlConn.CreateCommand() $SqlCmd.commandtext = 'delete top(1) from dbo.B' $SqlCmd.ExecuteScalar() #方法三,查询显示 $SqlCmd.commandtext = 'select name,recovery_model_desc,log_reuse_wait_desc from sys.databases' $SqlAdapter = New-Object System.Data.SqlClient.SqlDataAdapter $SqlAdapter.SelectCommand = $SqlCmd $set = New-Object data.dataset $SqlAdapter.Fill($set) $set.Tables[0] | Format-Table -Auto #关闭数据库连接 $SqlConn.close()