且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

通过PowerShell脚本使用MySQL控制台

更新时间:2023-12-05 18:03:58

您要尝试执行的操作将不起作用,因为您的代码要从mysql.exe退出后才能到达show databases;.在脚本中使用mysql.exe的通常方法是在每个查询中运行可执行文件:

What you're trying to do won't work, because your code won't get to the show databases; until you exit from mysql.exe. The usual way to use mysql.exe from a script is to run the executable with each query:

$db   = 'testasset'
$user = 'asset'
$pass = 'test'

$mysql  = 'C:\Users\I16A1\Downloads\mysql\bin\mysql.exe'
$params = '-u', $user, '-p', $pass, $db

& $mysql @params -e 'SHOW DATABASES'
& $mysql @params -e '...'
...

使用 splatting 提供常用参数.

通常,您还需要添加参数-B(--batch,非交互式执行,没有奇特的输出格式)和-N(--skip-column-names,不显示输出中的列标题)以获取更多信息这样的可消化"输出:

Normally you'd also add the parameters -B (--batch, non-interactive execution, no fancy output formatting) and -N (--skip-column-names, don't show column titles in output) to get more "digestible" output like this:

information_schema
mysql
performance_schema
test

与其获取这样的默认输出,不如将数据解析出表以进行进一步处理:

instead of getting default output like this, that would require parsing the data out of the table for further processing:

+--------------------+
| Database           |
+--------------------+
| information_schema |
| mysql              |
| performance_schema |
| test               |
+--------------------+


话虽如此,比使用命令行客户端更好的方法是使用.网络连接器,例如像这样:


With that said, a much better approach than working with the commandline client would be using the .Net Connector, e.g. like this:

$server = 'localhost'
$db     = 'testasset'
$user   = 'asset'
$pass   = 'test'

$cs = "server=$server;user id=$user;password=$pass;database=$db;pooling=false"

[void][Reflection.Assembly]::LoadWithPartialName('MySQL.Data')

$cn = New-Object MySql.Data.MySqlClient.MySqlConnection
$cn.ConnectionString = $cs
$cn.Open()

$cmd= New-Object MySql.Data.MySqlClient.MySqlCommand
$cmd.Connection  = $cn
$cmd.CommandText = 'SHOW DATABASES'
$reader = $cmd.ExecuteReader()

$tbl = New-Object Data.DataTable
$tbl.Load($reader)
$reader.Close()
$cn.Close()

$tbl | Format-Table -AutoSize

这样,您获得的输出将是实际的对象,而不是字符串.

That way the output you get will be actual objects instead of strings.