Here is a snippet from a PowerShell script:
$sql.CommandText = "CREATE DATABASE IF NOT EXISTS ``$dbName``;"
$rowsInserted = $sql.ExecuteNonQuery()
$sql.CommandText = "USE ``$dbName``;"
$rowsInserted = $sql.ExecuteNonQuery()
The CREATE DATABASE command works fine. The USE command does not. I get no error message from the Powershell ISE. $rowsInserted is 1 when I execute the CREATE DATABASE command and 0 when I execute the USE command.
I am running the ISE as an administrator. I have created the database outside of PowerShell and executed the USE command first. Still doesn't work. The database name is as simple as "test".
All the commands work from MySQL Workbench and from a command window.
Any help would be much appreciated.
2 Answers 2
When you use a database connection via ADO.NET or the MySQL Connector, each SQL command executes in its own session context unless you explicitly keep the same open connection.
However, even with the same connection, the USE statement is ignored by the connector because the connector does not persist a change in default database context through USE. Instead, the "default database" must be specified in the connection string.
When you do this in PowerShell:
$sql.CommandText = "CREATE DATABASE IF NOT EXISTS `$dbName`;"
$rowsInserted = $sql.ExecuteNonQuery()
This works because CREATE DATABASE is a DDL command (Data Definition Language). It returns 1 row affected, meaning successfully executed.
But :
$sql.CommandText = "USE `$dbName`;"
$rowsInserted = $sql.ExecuteNonQuery()
This doesn’t "fail" — but it also doesn’t do what you expect. $rowsInserted is 0 because USE doesn’t affect any rows. More importantly: USE has no effect on the connection object.
As a solution Specify the database name in your connection string when you need to work in a specific database.
$connectionString = "server=localhost;uid=root;pwd=yourPassword;database=$dbName"
$sql = New-Object MySql.Data.MySqlClient.MySqlCommand
$sql.Connection = New-Object MySql.Data.MySqlClient.MySqlConnection($connectionString)
$sql.Connection.Open()
Now you can execute commands directly within that database context, without needing USE.
Comments
My misunderstanding. The return value of ExecuteNonQuery appears to be the number of rows inserted. The USE command does not insert any rows, so the return value is zero.
$sql?use(pun intended)