首页 > 数据库 >PowerShell 连接 SQL SERVER/MySQL 数据库进行操作

PowerShell 连接 SQL SERVER/MySQL 数据库进行操作

时间:2023-01-10 12:05:18浏览次数:80  
标签:SqlConn Object string SQL SERVER Connection Command MySQL Data


 

#配置信息
$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()

 

Function GetSqlConnection{
Param(
[Parameter(position = 0 , Mandatory = $true)][string]$SQLIP,
[Parameter(position = 1 , Mandatory = $true)][string]$SQLPort,
[Parameter(position = 2 , Mandatory = $true)][string]$SQUser,
[Parameter(position = 3 , Mandatory = $true)][string]$SQLPwd,
[Parameter(position = 4 , Mandatory = $true)][string]$Database
)
$ConnString = "Data Source=$($SQLIP),$($SQLPort);Initial Catalog=$($Database);User ID=$($SQUser);Password=$($SQLPwd)"
Try{
$SqlConn = New-Object System.Data.SqlClient.SqlConnection $ConnString
$SqlConn.Open()
Return $SqlConn
}
Catch{
Write-Warning $_
Return $Null
}
}

Function ExecuteSQL{
Param(
[Parameter(position = 0 , Mandatory = $true)]$SqlConn,
[Parameter(position = 1 , Mandatory = $true)][string]$SqlString
)
Try{
$SqlCmd = New-Object System.Data.SqlClient.SqlCommand
$SqlCmd.CommandText = $SqlString
$SqlCmd.Connection = $SqlConn
$Reader= $SqlCmd.ExecuteReader()
$DataTable = New-Object System.Data.DataTable
$DataTable.Load($Reader)
}
Catch {
Write-Warning $_
Return $Null
}
Return $DataTable
}

Function CloseSqlConnection{
Param(
[Parameter(position = 0 , Mandatory = $true)]$SqlConn
)
If ($sqlConn.State -eq 'Open'){
$SqlConn.Close()
}
}


#示例
$SqlString = "select top 5 name from sys.databases "
$SqlString2 = "select top 5 name from sys.objects "

$SqlConn = GetSqlConnection $SQLIP $SQLPort $SQUser $SQLPwd "master"
$Data = ExecuteSQL $SqlConn $SqlString
$Data2 = ExecuteSQL $SqlConn $SqlString2
CloseSqlConnection $SqlConn

Write-Host ($Data).ItemArray
Write-Host ($Data2).ItemArray

 

MySQL 连接操作:

[string]$S_MyLHost = '192.168.1.110'
[string]$S_MyDB = 'dbname'
[string]$S_MyUser = 'myuser'
[string]$S_MyPWD = 'mypwd'

[string]$T_MyLHost = '192.168.1.111'
[string]$T_MyDB = 'dbname_new'
[string]$T_MyUser = 'myuser'
[string]$T_MyPWD = 'mypwd'

[string]$S_ConnStr = "server=$($S_MyLHost);port=3306;uid=$($S_MyUser);pwd=$($S_MyPWD);database=$($S_MyDB);SslMode=None;"
[string]$T_ConnStr = "server=$($T_MyLHost);port=3306;uid=$($T_MyUser);pwd=$($T_MyPWD);database=$($T_MyDB);SslMode=None;"
#[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
#[void][system.reflection.Assembly]::LoadFrom("C:\Windows\System32\MySql.Data.dll")

Function GetSqlConnection(){
param(
[string]$ConnectionString=$null
)
try{
$Connection = New-Object MySql.Data.MySqlClient.MySqlConnection($ConnectionString)
$Connection.Open()
}
catch{
Write-Warning $_
Write-Warning $Error[0].Exception.InnerException
return $null
}
return $Connection
}

Function ExecuteQuery(){
param(
[string]$ConnectionString=$null,
[string]$SqlString=$null
)
$Connection = GetSqlConnection($ConnectionString)
if($Connection) {
try{
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand
$DataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter
$DataSet = New-Object System.Data.DataSet
$Command.Connection=$Connection
$Command.CommandText=$SqlString
$DataAdapter.SelectCommand=$Command
$NumberOfDataSets=$DataAdapter.Fill($DataSet, "data")
}
catch {
Write-Warning $_
return $null
}
Finally {
$Connection.close()
}
}
return $DataSet
}

#未使用
Function ExecuteNonQuery(){
param(
[string]$ConnectionString=$null,
[string]$SqlString=$null
)
$Connection = GetSqlConnection($ConnectionString)
if($Connection) {
try{
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand
$Command.Connection = $Connection
$Command.CommandText = $SqlString
$RowsAffected=$Command.ExecuteNonQuery()
write-host $RowsAffected
}
catch {
Write-Warning $_
return $false
}
Finally {
$Connection.close()
}
}
return $true
}


Function ExecuteNonQuery_change_info(){
param(
[string]$S_ConnStr=$null,
[string]$T_ConnStr=$null
)

[string]$S_Sql="SELECT `id`, `name` FROM tab;"
[string]$T_Sql="INSERT INTO tab_test(`id`, `name`)VALUES(@id, @name)"

$Connection = GetSqlConnection($T_ConnStr)
$DataSet = ExecuteQuery $S_ConnStr $S_Sql

if($Connection) {
try{
foreach($Row in $DataSet.tables[0]){
$Command = New-Object MySql.Data.MySqlClient.MySqlCommand
$Command.Connection = $Connection
$Command.CommandText = $T_Sql
$Command.Parameters.AddWithValue("@id", $Row.id) | Out-Null
$Command.Parameters.AddWithValue("@name", $Row.name) | Out-Null
$RowsAffected=$Command.ExecuteNonQuery()
}
}
catch {
Write-Warning $_
return $false
}
Finally {
$Connection.close()
}
}
return $true
}

ExecuteNonQuery_change_info $S_ConnStr $T_ConnStr

 

 

 

参考: ​​ Windows PowerShell:使用 PowerShell 处理数据库​

 


标签:SqlConn,Object,string,SQL,SERVER,Connection,Command,MySQL,Data
From: https://blog.51cto.com/hzc2012/6000168

相关文章

  • oracle ,mysql,sqlserver 挑选特定行号的纪录
    oracle:SELECT*FROMtableWHEREROWNUM<101;minusSELECT*FROMtableWHEREROWNUM<91;mysql:select*fromtablelimit5,5第一个5是开始的行号,第二个5是选择纪录......
  • mysql event 实例
    今天一网友求助,每天早上8点自动将A表中的10条数据插入B表,然后在A表中删除那10条数据。现测试功能:  有table_a和table_b表,每30秒table_a有2条数据插入到table_b表,然后删......
  • SQLServer 从xml 文件中提取节点数据到数据库中
    <?xmlversion="1.0"encoding="utf-8"?><!--editedwithXMLSpyv2010(http://www.altova.com)byfengshuai(founder)--><Root><Frame><Item><ID>0</ID><Nu......
  • 使用 NineData 高效编写 SQL
    SQL是StructuredQueryLanguage的缩写,中文翻译为“结构化查询语言”。它是关系型数据库的标准语言,所有的关系型数据库管理系统(RDBMS),比如MySQL、Oracle、SQLServer、P......
  • 【转发】oracle sqlplus 创建和调用存储过程(procedure)
    一、创建存储过程1、oracle创建存储过程的语法oracle存储过程语法格式CREATEORREPLACEPROCEDUREprocedureNameISDECLARE.......BEGIN...........END;......
  • docker安装mysql
    搜索镜像名字dockersearchmysql 在网页端搜索版本列表:https://hub.docker.com/  点击标题,在下面选出需要的版本号拉取镜像 dockerpullmysql:8.0 ......
  • 关于replace(): MySQL批量替换指定字段字符串
    UPDATEtb1SETf1=REPLACE(str,from_str,to_str) 在字符串 str中所有出现的字符串from_str均被to_str替换,然后返回这个字符串 实例:updatebase_giftsetimg_ur......
  • mysql8.0特性管理相关
    转自:https://mp.weixin.qq.com/mp/appmsgalbum?__biz=Mzg5OTY2MjU5MQ==&action=getalbum&album_id=2435603183193505795&scene=173&from_msgid=2247491832&from_itemidx=1&......
  • mysql COALESCE函数
    COALESCE(value,…)是一个可变参函数,可以使用多个参数。作用:接受多个参数,返回第一个不为NULL的参数,如果所有参数都为NULL,此函数返回NULL;当它使用2个参数时,和IFNULL函数作用......
  • 完全卸载MySQL服务的方法
    1.重新运行安装文件,单击remove移除mysql。此时安装目录中的文件没有完全移除,需要手动删除安装目录的Mysql文件夹。2.如果MySQL服务没有移除的话,以管理员方式运行cmd命令:sc......