我在 powershell 中编写了一个脚本,该脚本应该连接到 MySQL 服务器,创建一个新数据库,然后对该数据库运行查询命令。我有一个预制的 .sql 文件,其中包含要执行的所有命令,但是我的代码似乎存在问题,它从未真正执行过 .sql 文件。任何帮助,将不胜感激。我的代码如下。
[void][system.reflection.Assembly]::LoadWithPartialName("MySql.Data")
#Creates a connection to the server
$connStr ="server=mySql;Persist Security Info=false;user id=" + "username" + ";pwd=" + "pass" + ";"
$conn = New-Object MySql.Data.MySqlClient.MySqlConnection($connStr)
#Open connection
$conn.Open()
#Drops database if it currently exists
$cmd = New-Object MySql.Data.MySqlClient.MySqlCommand
$cmd.Connection = $conn
$cmd.CommandText = "DROP DATABASE IF EXISTS " + $dbname
$cmd.ExecuteNonQuery()
#Create the new database
$cmd.CommandText = 'CREATE SCHEMA `' + $dbname + '`'
$cmd.ExecuteNonQuery()
#Load the sql file
$sql = (Get-Content C:\"path to sql file") -join "'r'n"
$cmd.CommandText = $sql
#Close connection
$conn.Close()