--- tags: Python,資料庫 --- # Python x sqlite ## 1. 簡介 1. SQlite 屬於輕量化的關聯式的資料庫,在手機應用以及不需要非常多的資料庫下都可以找到足跡 [官方網站](https://sqlite.org/index.html) 2. 資料庫特性是當用戶端完成一筆建立資料/查詢資料/插入資料時,必須送出存檔,才算是完成資料存取的操作,不然一直暫存在記憶體內,是無法提供其他操作存取或更新的。 ## 2.Python操作/語法 Python 內建sqlite drive,不需另外安裝使用。 套件載入方式`import sqlite3` 基本查詢語法依循SQL標準語法: ;代表該行語法結束 建立????? `CREATE DATABASE <DATABASENAME>;` `CREATE TABLE <TABLENAME> (<TABLE 欄位 )` 查詢資料 `select <search condition> from <table name> where <sub condition>;` 插入資料 `INSERT INTO table_name (column1, column2, column3, ...) VALUES (value1, value2, value3, ...);` 更新資料 `UPDATE table_name SET column1 = value1, column2 = value2, ... WHERE condition;` --- 結合到python 就變成這樣 ``` import sqlite3` c = conn.cursor() # Create table c.execute('''CREATE TABLE stocks (date text, trans text, symbol text, qty real, price real)''') # Insert a row of data c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)") # Save (commit) the changes conn.commit() # We can also close the connection if we are done with it. # Just be sure any changes have been committed or they will be lost. conn.close() ``` ## 3.程式範例 本次使用pandas 直接呼叫爬蟲,取用臺灣銀行的匯率 ,另外使用了sqlalchemy 這個套件讓pandas 可以直接操作資料庫 ``` import pandas as pd from sqlalchemy import create_engine count = 0 col1s = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17] # u"string" u的意思代表以UTF方式進行編碼 col2s = [u"幣別", u"現金-本行買進", u"現金-本行賣出", u"即期-買進", u"即期-賣出"] url = ("https://rate.bot.com.tw/xrt?Lang=zh-TW") df = pd.read_html(url)[0] df.columns = col1s table = df.drop(columns=[6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17]) # table = df.drop(df.columns(lambda ,axis=1,inplace=True)) table.columns = col2s """ #"[\u4e00-\u9fa5]" 表示以正則表示式 UTF8匹配所有中文 .map(lambda x: str(x)[:-5]) 以MAP和LAMBDA 小迴圈逐一比對字串索引值倒數5個字元 .map(lambda x: str(x)[2:5]) 以MAP和LAMBDA 小迴圈逐一比對字串索引值2~5個字元 """ table.replace('[\u4e00-\u9fa5]', "", inplace=True, regex=True) table[u"幣別"] = table[u"幣別"].map(lambda x: str(x)[2:5]) # table.replace = re.search("[\u4e00-\u9fa5]", table[u"幣別"], regex=True) print(table) engine = create_engine('sqlite:///exchangerate.db', echo=True) sqlite_connection = engine.connect() sqlitetable = "rate" table.to_sql(sqlitetable, sqlite_connection, if_exists='fail') sqlite_connection.close() ``` ### 驗證 1. 下載DB BROSWER 2. 開啟sqlite 資料庫,確認資料有進資料庫嚕^^ ![](https://i.imgur.com/MPQh3BJ.png) ## 4.後記. Python 官網文件 [DB-API 2.0 interface for SQLite databases](https://docs.python.org/3/library/sqlite3.html) W3school [Learn SQL](https://www.w3schools.com/sql/default.asp) [SQLAlchemy offical web site](https://www.sqlalchemy.org/)