【資料分析】如何用Python執行SQL語法

Kao Jia
8 min readMay 27, 2023

--

本文記錄了如何用Python去串SQL,提供直接下載SQL管理系統之外,其他可以執行SQL的方法。

有些數據分析職缺在面試時會考SQL,在考試時我們可以自己建立一個假的資料庫,幫助我們檢查考試的內容是否正確。以下分為兩個部分說明,一是在我們兩手空空沒有資料庫的情況下,需要從頭開始建立資料庫。二是已有資料庫的情況,直接使用Python串接。

需要注意的是,本文在Python上串的資料庫語言為SQLite,實際執行時可能會因爲不同的SQL管理系統而有差異。

目錄
1. 在Python建立資料庫
1.1 從0開始做資料庫
1.2 從Excel召喚資料庫
2. 已有資料庫的情況

Python建立資料庫:

  1. 從 0 開始做資料庫
import sqlite3

db = sqlite3.connect('practice2023.db') #建立資料庫
cursor = db.cursor()#創建連結

#創建資料表company,設定欄位名與欄位type
cursor.execute('''
CREATE TABLE COMPANY
(Store_ID CHAR(50),
Salesperson CHAR(50),
Sales INT
);

''')
db.commit()

由於在寫Python可能會有重複執行的情況,此時可能會跳出錯誤:“已有該資料表”,偷懶不想update的話可以補一個「刪除資料表」在創建資料表之前,讓每次執行前先刪除資料表再創建資料表。

cursor.execute('''
DROP TABLE COMPANY
''')
db.commit()
#一行一行插入資料
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('1', 'Aaron' , 374 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('1', 'Beatrice' ,492 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('1', 'Cathy' , 430 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('2', 'Dan' ,462 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('2', 'Elmo' ,747 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('2', 'Frank' ,1332 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('2', 'Gina' ,898 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('2', 'Harry' ,603 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('3', 'Isabel' ,247 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('3', 'Jimmy' ,1030 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('3', 'Kara' ,1030 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('3', 'Lamar' ,1314 )")
cursor.execute("INSERT INTO COMPANY (Store_ID,Salesperson,Sales) \
VALUES ('3', 'Mary' ,462 )")
db.commit()
def run_query(query):
return pd.read_sql_query(query, db)#創造一個function

之後將SQL 包在以下語法中,就可以執行了!

#將SQL語法包在Query中
Query = '''
select * from COMPANY;
'''
run_query(Query)#執行Query

2. 從 Excel 召喚資料庫

這是我最推薦的考試時模擬資料庫的方法。
先將考題中的表格先貼到Excel上,每一個 Excel 的 sheet 代表一個資料表,接著從Python讀取Excel的資料。本例中假設我們將四個不同的資料表:Course, SC, Student, Teacher。

import sqlite3
import pandas as pd

df1 = pd.read_excel('practice_of_sql.xlsx', sheet_name='Course') #讀取Excel檔案
df2 = pd.read_excel('practice_of_sql.xlsx', sheet_name='SC') #讀取Excel資料集檔案
df3 = pd.read_excel('practice_of_sql.xlsx', sheet_name='Student') #讀取Excel資料集檔案
df4 = pd.read_excel('practice_of_sql.xlsx', sheet_name='Teacher') #讀取Excel資料集檔案
db = sqlite3.connect('50_practice_of_sql.db')  #建立資料庫
cursor = db.cursor() #創建連結

# 建立第一張資料表 Course (括弧裡面為欄位名稱)
cursor.execute('CREATE TABLE Course(CId, Cname, TId)')
db.commit()
df1.to_sql('Course', db, if_exists='append', index=False) #如果資料表存在,就寫入資料,否則建立資料表

#建立第二張資料表 SC
cursor.execute('CREATE TABLE SC(SId, CId, score)')
db.commit()
df2.to_sql('SC',db, if_exists='append', index=False)

#建立第三張資料表 Student
cursor.execute('CREATE TABLE Student(SId, Sname, Sage, Ssex)')
db.commit()
df3.to_sql('Student',db, if_exists='append', index=False)

#建立第四張資料表 Student
cursor.execute('CREATE TABLE Teacher(TId, Tname)')
db.commit()
df4.to_sql('Teacher',db, if_exists='append', index=False)
def run_query(query):
return pd.read_sql_query(query, db)#創造一個function

之後將SQL 包在以下語法中,就可以執行了!

#將SQL語法包在Query中
Query = '''
select * from student;
'''
run_query(Query)#執行Query

已有資料庫的情況:

當我們已有資料庫檔案(.db),則可以直接用Python去串資料庫,語法如下:

import sqlite3
import pandas as pd
db=sqlite3.connect("link.db") #link.db是指存放在本機端的資料庫路徑

def run_query(query):
return pd.read_sql_query(query, db)#創造一個function

之後將SQL 包在以下語法中

#將SQL語法包在Query中
Query = '''
select * from student;
'''
run_query(Query)#執行Query

就可以執行了!

--

--