Powershell操作MySQL

最近再用Python写一些监控脚本,并将监控数据输出到MySQL中,最后通过Python抓取MySQL中的数据进行监控汇总告警

考虑到一些微软产品使用Powershell更为方便,于是找了些资料,尝试Powershell操作M有SQL的可能性,方法如下:

在使用Powershell操作MySQL之前,我们需要下载MySQL Connector/NET(Connector/NET is a fully-managed ADO.NET driver for MySQL)

目前最新版本为:8.0.12,下载连接https://dev.mysql.com/downloads/connector/net/

下载后得到msi,安装路径:C:\Program Files (x86)\MySQL\MySQL Connector Net 8.0.12\Assemblies\v4.5.2\MySql.Data.dll,我们主要就是

使用这个dll文件,将其copy出来,放到脚本服务器上。

然后,我们通过System.Reflection中的Assembly Class来加载,操作程序集(MySql.Data.dll),核心代码(红色字体需自定义):

$mySQLDataDLL = "C:\mysql\MySql.Data.dll"  #dll文件的绝对路径
[void][System.Reflection.Assembly]::LoadWithPartialName("MySql.Data")
[void][system.reflection.Assembly]::LoadFrom($mySQLDataDLL)
 
#连接MySQL
$Server = " xxx.xxx.xxx.xxx"                        #IP地址
$Database = " database name"                   
$user = " username"
$Password = " xxxxxxx"
$charset = "utf8"
$connectionString = "server=$Server;uid=$user;pwd=$Password;database=$Database;charset=$charset;SslMode=none"
$connection = New-Object MySql.Data.MySqlClient.MySqlConnection($connectionString)
$connection.Open()
 
#执行MySQL
$insert = "INSERT INTO Tables Name ( 依据表结构) VALUES(xxxxxxxxx);"
$insertcommand = New-Object MySql.Data.MySqlClient.MySqlCommand
$insertcommand.Connection = $connection
$insertcommand.CommandText = $insert
$insertcommand.executenonquery()
 
#关闭连接
$connection.Close()
 
执行后,我们查看一下MySQL中是否有新数据
 

猜你喜欢

转载自www.cnblogs.com/zhr1217/p/9686514.html