MonsterSupreme / Blog

Blog of Monster Supreme
2 stars 0 forks source link

Azure Cloud Shell and Python mssql-cli Tool #8

Open MonsterSupreme opened 3 years ago

MonsterSupreme commented 3 years ago

因為需要在一個 Browser-Only 的環境教大家 Azure Synapse Analytics,過程中需要一個可以管理 SQL Server 的工具,雖然 Azure Data Studio 或是 Visual Studio Code + SQL Server (mssql) Extension 很棒,可是畢竟都需要安裝。找了一下,沒找到適合的線上工具,結果今天突然想到,Azure Portal 的 Cloud Shell 有支援 Python,所以我就想到,可以安裝 dbcli/mssql-cli 這個用 Python 寫的 CLI 工具啊!

打開 Cloud Shell:

Requesting a Cloud Shell.Succeeded.
Connecting terminal...

Welcome to Azure Cloud Shell

Type "az" to use Azure CLI
Type "help" to learn about Cloud Shell

MOTD: Switch to PowerShell from Bash: pwsh

VERBOSE: Authenticating to Azure ...
VERBOSE: Building your Azure drive ...
PS /home/kc>

確認 Python 版本 (2.7/3.6 或以上就可以):

PS /home/kc> python -V
Python 3.7.3

安裝 mssql-cli 工具:

PS /home/kc> pip install mssql-cli
Defaulting to user installation because normal site-packages is not writeable
...
WARNING: You are using pip version 20.2.4; however, version 21.1.2 is available.
You should consider upgrading via the '/usr/bin/python3 -m pip install --upgrade pip' command.

再來記得把 Cloud Shell 的 IP 加入 Firewall 的 IP White List:

PS /home/kc> $cloudshellip = (Invoke-RestMethod -Uri https://ipinfo.io/json).ip
PS /home/kc> New-AzSqlServerFirewallRule -FirewallRuleName cloudshell \
-StartIpAddress $cloudshellip \
-EndIpAddress $cloudshellip \
-ServerName SQLServer名稱 \
-ResourceGroupName 資源群組名稱

ResourceGroupName : 資源群組名稱
ServerName        : SQLServer名稱
StartIpAddress    : 1.2.3.4
EndIpAddress      : 1.2.3.4
FirewallRuleName  : cloudshell

就可以開始連線了:

PS /home/kc> mssql-cli -S SQLServer名稱.database.windows.net -U 帳號 -d 資料庫名稱
Password:
sqldw> 

連線成功,下個 Query 看看:

sqldw> select * from sys.external_tables;
Time: 0.654s
+-------------+-------------+----------------+-------------+--------------------+--------+-------------+-------------
| name        | object_id   | principal_id   | schema_id   | parent_object_id   | type   | type_desc   | create_date
|-------------+-------------+----------------+-------------+--------------------+--------+-------------+-------------
| ext_pokemon | 1022626686  | NULL           | 1           | 0                  | U      | USER_TABLE  | 2021-05-31 1
+-------------+-------------+----------------+-------------+--------------------+--------+-------------+-------------
(1 row affected)
sqldw> 

結束也很簡單:

sqldw> quit
PS /home/kc>

於是,在 Azure Portal 裡頭,就有一個 SQL Server 的 CLI 工具可以使用囉!