昨日把資料表建立完畢,也建立了資料表和嘗試使用Azure Data Stadio
建立資料,之後要用我們的主角Python把資料匯進去。但在這之前,要先從本機使用Python連線到Azure。
本次的範例為:Day11_saveToAzureDB.py
我們已經使用Azure Data Stadio
手動輸入資料到Stock
資料表中,但這樣人工作業太多,每個股票每一天的交易明細,像是開盤價
、最高價
、最低價
、收盤價
(也就是之前所的開高低收,open
、high
、low
、close
)都要手動輸入,會打到天荒地老都還沒有結束,這時候就是Python上場之時,運用程式可以快速的批次作業,取資料的時候可以整批取得,當然也可以整批進去資料庫中。
首先要安裝的套件是資料庫處理神器:ODBC
(詳細資料可參考WIKI),也就是我們用來連線資料庫或是與資料庫溝通的工具。安裝方式也是使用我們的pipenv
:
pipenv install pyodbc
安裝完畢後,開始執行我們的程式碼(可以參考Day11_saveToAzureDB.py):
import pyodbc
server = "ey-finance.database.windows.net"
database = "finance"
username = "我的登入帳號"
password = "我的密碼"
driver= "{ODBC Driver 17 for SQL Server}"
with pyodbc.connect(
f"DRIVER={driver};SERVER={server};PORT=1433;DATABASE={database};UID={username};PWD={password}"
) as conn:
with conn.cursor() as cursor:
cursor.execute("SELECT * FROM Stock;")
row = cursor.fetchone()
print("This is data in my Azure.....by Eyelash")
while row:
print(f"{row[0]} {row[1]} {row[2]} {row[3]} {row[4]} {row[5]}")
row = cursor.fetchone()
結果發現(部分資料用...
取代):
....
File "/Users/.../12-ithome/Day11_saveToAzureDB.py", line 1, in <module>
import pyodbc
ImportError: dlopen(/Users/.../python3.8/site-packages/pyodbc.cpython-38-darwin.so, 2): Library not loaded: /usr/local/opt/unixodbc/lib/libodbc.2.dylib
Referenced from: /Users/.../python3.8/site-packages/pyodbc.cpython-38-darwin.so
Reason: image not found
可以看到仍無法執行。仔細看一下內容,發現沒有Library「unixodbc
」,看到這個issue知道原來少個ODBC Driver的管理器。那我們就來安裝他吧!
使用brew
:
brew install unixodbc
可是安裝後再執行,仍發生錯誤:
'01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)")
這缺少了ODBC Driver 17 for SQL Server
,所以需要三個步驟安裝driver。
在terminal中下三個指令:
brew tap microsoft/mssql-release https://github.com/Microsoft/homebrew-mssql-release
brew update
HOMEBREW_NO_ENV_FILTERING=1 ACCEPT_EULA=Y brew install msodbcsql17 mssql-tools
安裝完成後會有這樣的訊息:
==> msodbcsql17
If you installed this formula with the registration option (default), you'll
need to manually remove [ODBC Driver 17 for SQL Server] section from
odbcinst.ini after the formula is uninstalled. This can be done by executing
the following command:
odbcinst -u -d -n "ODBC Driver 17 for SQL Server"
備註:
如果只是跑HOMEBREW_NO_ENV_FILTERING=1 ACCEPT_EULA=Y brew install msodbcsql17 mssql-tools
,會有這樣的錯誤:
Error: No available formula with the name "msodbcsql17"
==> Searching for a previously deleted formula (in the last month)...
Error: No previously deleted formula found.
==> Searching for similarly named formulae...
Error: No similarly named formulae found.
==> Searching taps...
==> Searching taps on GitHub...
Error: No formulae found in taps.
安裝完畢後,再跑一次看看,發現就可以跑囉~
出來的結果會是:
This is data in my Azure.....by Eyelash
DD95BD53-28B1-4D48-9D6F-6E649233C774 TW 2330 S ??? 2020-01-01
這資料看起來有點奇怪,我們的台積電怎麼不見了?只有???
,我們再來探討一下原因。