1、在使用PowerShell操作MySQL之前,需要下载MySQL Connector Net 6.9.5(自行度娘)
2、下载安装后,需要找到其安装的目录,并找到用于连接和操作MySQL的DLL文件;如:
C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.5\Assemblies\v2.0\MySql.Data.dll(V2.0为NET的版本)
3、核心语句为:
[void][system.Reflection.Assembly]::LoadFrom("C:\Program Files (x86)\MySQL\MySQL Connector Net 6.9.5\Assemblies\v2.0\MySql.Data.dll") | Out-Null
连接MySQL:
$Server="127.0.0.1"
$Database="sql"
$user="root"
$Password= ""
$charset="utf8"
$connectionString = "server=$Server;uid=$user;pwd=$Password;database=$Database;charset=$charset"
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection($connectionString)
$connection.Open()
执行SQL:
$insertsql = "INSERT INTO ad(姓,名,部门) VALUES('XXX','XXX','XXX');"
$insertcommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$insertcommand.Connection=$connection
$insertcommand.CommandText=$insertsql
$insertcommand.ExecuteNonQuery()
关闭连接:
$connection.Close()