자바스크립트를 활성화 해주세요

p047 Powershell로 Mysql 다루기

 ·  ☕ 3 min read

mysqlite를 다루는 포스트를 작성하고 난 뒤, mysql은? 하는 생각이 들어 작성해 봤습니다. 가장 많이 사용하는 database인데 이를 powrshell에서 사용하는 포스트를 볼 수 없다니요. 그래서 작성해 봤습니다.

단, 여기에서는 SimplySql 라는 모듈을 사용합니다. 이 모듈이 가장 최선의 모듈인지는 전부 사용해 보지 않아서 잘 모르겠습니다. 우선 Powershell Gallery에서 가장 우선으로 검색되는 모듈을 사용합니다.

goormide에서 container를 작성할 때, 제일 아래에 mysq을 함께 설치하는 옵션이 있습니다. 또, mysql-cli도 함께 설치할 수 있는 지 설정하는 것이 가능한데, Empty Project를 사용해서 Ubuntu 18.04 를 사용하면서 mysql도 함께 설치한 컨테이너를 사용합니다.

mysql-ctl

다음은 goormide에서 제공하는 커맨드입니다. 그냥 systemctl start mysql로는 mysqld가 정상적으로 실행되지 않을 수 있습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
root@goorm:~# mysql-ctl
Usage: mysql-ctl [install|start|stop|cli|status]
root@goorm:~# mysql-ctl start

MySQL 5.7 database added.  Please make note of these credentials:

       Root User: root
   Database Name: mysql

 * Starting MySQL database server mysqld
No directory, logging in with HOME=/
   ...done.

powrshell 7 설치

늘 사용하는 스크립트입니다. 구글검색에서 Installing PowerShell on Linux로 검색하면 다음의 마이크로소프트의 페이지를 소개해 줄 것입니다.

https://docs.microsoft.com/en-us/powershell/scripting/install/installing-powershell-core-on-linux?view=powershell-7

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
# Download the Microsoft repository GPG keys
wget -q https://packages.microsoft.com/config/ubuntu/18.04/packages-microsoft-prod.deb

# Register the Microsoft repository GPG keys
sudo dpkg -i packages-microsoft-prod.deb

# Update the list of products
sudo apt-get update

# Enable the "universe" repositories
sudo add-apt-repository universe

# Install PowerShell
sudo apt-get install -y powershell

# Start PowerShell
pwsh

create mysql user

mysql 쿼리로 user를 생성합니다. 실행하는 쿼리는 다음과 같습니다.

CREATE USER 'tkim'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON * . * TO 'tkim'@'localhost';
FLUSH PRIVILEGES;

mysql cli를 실행하면 다음과 같은 결과가 나옵니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
root@goorm:~# mysql
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 8
Server version: 5.7.31-0ubuntu0.18.04.1 (Ubuntu)

Copyright (c) 2000, 2020, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> CREATE USER 'tkim'@'localhost' IDENTIFIED BY 'password';
Query OK, 0 rows affected (0.27 sec)

mysql> GRANT ALL PRIVILEGES ON * . * TO 'tkim'@'localhost';
Query OK, 0 rows affected (0.00 sec)

mysql> FLUSH PRIVILEGES;
Query OK, 0 rows affected (0.11 sec)

SimplySql 모듈

이제 Powershell에서 Mysql을 다루는 코드를 살펴보겠습니다.

모듈 설치

1
2
install-module SimplySql
import-module SimplySql

Connection열기

1
Open-MysqlConnection -Server "localhost" -Database "mysql" -UserName tkim -Password "password"

Query 실행하기

1
$data = Invoke-SqlQuery -query "SELECT * FROM user"

Parameter로 실행하기

1
$data = Invoke-SqlQuery -query "SELECT * FROM someTable WHERE someCol = @var" -Parameters @{var = 'a value'}

Connection 닫기

1
Close-SqlConnection

실행한 결과는 다음과 같습니다. Select 쿼리 뿐이지만 정상적으로 실행되는 것을 확인할 수 있습니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
PS /root> Open-MysqlConnection -Server "localhost" -Database "mysql" -UserName tkim -Password "password"
WARNING: You are using -UserName and -Password, these options are deprecated and will be removed in the future.  Please consider using -Credential.
PS /root> $data = Invoke-SqlQuery -query "SELECT * FROM user"
PS /root> $data | ft

Host      User             Select_priv Insert_priv Update_priv Delete_priv Create_priv Drop_priv Reload_priv Shutdown_priv
----      ----             ----------- ----------- ----------- ----------- ----------- --------- ----------- -------------
localhost root             Y           Y           Y           Y           Y           Y         Y           Y
localhost mysql.session    N           N           N           N           N           N         N           N
localhost mysql.sys        N           N           N           N           N           N         N           N
localhost debian-sys-maint Y           Y           Y           Y           Y           Y         Y           Y
localhost tkim             Y           Y           Y           Y           Y           Y         Y           Y

기타

이 모듈은 DB의 종류에 따라서 Connnection을 여는 방법이 다릅니다. 이는 메뉴얼을 참조하는 것이 좋겠습니다.

그리고 일반적인 예제
https://github.com/mithrandyr/SimplySql/wiki/Examples

이상으로 SimplySql 사용해서 mysql을 다루어 보았습니다. Invoke-SqlCmd2와 비교해서 어떤 것이 더 냐은 지 확인하지는 않았지만, 다루는 데는 문제가 없는 것 같습니다.

레퍼런스

공유하기

tkim
글쓴이
tkim
Software Engineer