Powershell 连接MySQL

2022-12-12 10:05:56 来源:51CTO博客


【资料图】

powershell连接SQL Server一般都是直接使用Invoke-sqlcmd,这个很方便,但是有时候还是会需要连接到其他数据库,像MySQL。

连接MySQL是通过.net框架的,所以必须先安装 MySQL .Net Connector (​​http://dev.mysql.com/downloads/connector/net/​​)。如果不想安装MySQL .Net connector 也可以直接在其他已安装的机器上拷贝MySql.Data.dll 到需要使用的机器上。

连接方式:如果是安装了MySQL .Net Connector

[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")

如果是直接通过MySQL.Data.dll文件:

$mySQLDataDLL = "C:\scripts\mysql\MySQL.Data.dll"[void][system.reflection.Assembly]::LoadFrom($mySQLDataDLL)

代码内容如下:

[void][system.Reflection.Assembly]::LoadFrom("C:\\Program Files (x86)\\MySQL\\MySQL Connector Net 8.0.16\\Assemblies\\v4.5.2\\MySql.Data.dll")$Server="10.2.3.144"$Database="test" #数据库名$user="user" #账户$Password="123456" #密码$connectionString = "server=$Server;uid=$user;pwd=$Password;database=$Database;charset=$charset"$connection = New-Object MySql.Data.MySqlClient.MySqlConnection($connectionString)$connection.Open()#GET 某个账户的MemeberID$getsql= "SELECT MEMBER_ID from  org_principal WHERE LOGIN_NAME = "$username""$getcommand = New-Object MySql.Data.MySqlClient.MySqlCommand($getsql, $connection)$dataAdapter = New-Object MySql.Data.MySqlClient.MySqlDataAdapter($getcommand)$getid = New-Object System.Data.DataSet$recordCount = $dataAdapter.Fill($getid)Write-Host "共有" $recordCount "条记录"$memberid=$getid.Tables.ROWS.MEMBER_ID#更新这个ID到AD绑定表中$insertsql = "INSERT INTO ctp_org_user_mapper (ID,TYPE,LOGIN_NAME,EX_LOGIN_NAME,EX_PASSWORD,EX_ID,MEMBER_ID,EX_UNIT_CODE) VALUES ("$userid","ad.member","$username","$username","null","670869647114347","$memberid","$usercnname");"$insertcommand = New-Object MySql.Data.MySqlClient.MySqlCommand$insertcommand.Connection=$connection$insertcommand.CommandText=$insertsql$insertcommand.ExecuteNonQuery()$connection.Close()

标签: 连接方式 一般都是

上一篇:win7将PowerShell升级到4.0
下一篇:天天快报!Linux系统如何知道端口号杀死进程