Вы можете подключиться к базе данных MySQL/MariaDB, получить данные из таблицы, добавить или обновить данные прямо из PowerShell скрипта. В этой статье мы рассмотрим несколько простых способов выполнения SQL запросов к удаленной базе данных MySQL (MariaDB) из консоли PowerShell.
Прежде всего проверьте, что удаленный SQL сервер разрешает удаленный подключения по порту 3306 (по умолчанию):
Test-NetConnection mysqlDBserver -port 3306
Затем на сервере MySQL разрешите пользователю удаленные подключения с вашего IP адреса или с любого хоста (замените IP на %):
PowerShell модуль SimplySql для подключения к БД MariaDB и MySQL
Для подключения и выполнения запросов к MySQL/MariaDB базе можно использовать универсальный PowerShell модуль SimplySql. Этот модуль можно установить из PowerShell Online Gallery:
Install-Module -Name SimplySql
Для подключения к MariDB/MySQL серверу используется командлет Open-MySQLConnection, а для выполнения SQL запросов — Invoke-SQLQuery.
Сохранить имя пользователя и пароль для подключения к SQL серверу:
Подключиться к базе данных MySQL/MariaDB на удаленном сервере:
$sqlConnect = Open-MySqlConnection -ConnectionName MyDBCon -Server 192.168.158.129 -Database myDB -Port 3306 -Credential $creds -WarningAction SilentlyContinue
Выполнить запрос к таблице MySQL с параметром:
$cityname="MSK"
$data = Invoke-SqlQuery -query "SELECT * FROM myDB WHERE city like '%$cityname%'"
Вставить данные в таблицу:
Обновить значение поля в таблице MySQL:
Invoke-SqlQuery -query "UPDATE myDB SET city = 'MSK' WHERE ID = 233"
Закрыть подключение к базе данных:
Close-SqlConnection -connectionname MyDBCon
Выполнение SQL запросов из PowerShell через MySQL коннектор
Примечание. Не обязательно ставить полную версию MySQL .NET Connector, достаточно скопировать на компьютер файл библиотеки MySql.Data.dll.
#подключение библиотеки MySql.Data.dll
Следующий скрипт с помощью SELECT запроса получит данные из таблицы БД и покажет их в консоли PowerShell.
Before I start I have looked at Invoke-Sqlcmd and I suppose I could go down that route, but I would like to update the current script without having to change to different CMD-lets etc.
I have a docker container that has a health check script powershell file.
This file uses System.Data.SqlClient.SqlConnection to create a connection to the DB and runs a basic query to check if the sql instance is running.
What I want to do is, once the health check logic is successful, run the contents of another .sql script file to seed the DB with some data.
$server = 'cas,1433'
$username = 'sa'
$password = 'myPass'
$database = 'cas'
try {
$connectionString = "Server=$server;Database=$database;Uid=$username;Pwd=$password"
$connection = New-Object -TypeName System.Data.SqlClient.SqlConnection -ArgumentList $connectionString
$connection.Open()
$command = $connection.CreateCommand()
$command.CommandText = "SELECT 1"
$result = $command.ExecuteScalar()
if ($result -eq 1) {
Write-Host "Success on health"
# Run the contents of a file called seed_data.ps1 (The file is in the directory as this script)
# assign the returned results from the script to $out
Write-Host $out
$connection.Close()
exit 0
}
else {
Write-Host "Health Failed"
$connection.Close()
exit 1
}
}
catch {
Write-Host $_.Exception.Message
$connection.Close()
exit 1
}
Side note. The docker compose file runs the health check on a loop, for example it runs every 10 seconds for a total of 10 times. So the issue isn’t that the health check isn’t working its just about getting the contents of the seed file to run.