Skip to main content

SQLite

Sqlite資料庫

  • Python內建資料庫
  • 輕量級關聯式資料庫
  • 需要使用sql語法進行溝通
  • Sqlite browser資料庫瀏覽器
  • 協助觀察sqlite資料庫內容的軟體
  • 請到sqlitebrowser下載64位元版本no installer並解壓縮
  • 執行DB Browser for SQLite.exe

Create新建資料庫及資料表

import sqlite3
conn = sqlite3.connect("myData.db") #連線資料庫,如果沒有會建立一個
sql = ''' Create table students( #設定sql指令
id int,
name text,
gender text)'''
conn.execute(sql) #執行sql指令建立資料表
conn.close() #關閉資料庫連線

Insert新增資料

import sqlite3
conn = sqlite3.connect("myData.db")
print("請輸入student資料")
while True:
newID = int(input("請輸入ID:")) #使用者輸入的字轉為整數
newName = (input("請輸入Name:") #使用者輸入名稱
newGender = input("請輸入gender:") #使用者輸入性別
x = (newID, newName, newGender) #做一個Tuple
sql = 'INSERT INTO students VALUES(?,?,?)' #設定sql指令
conn.execute(sql,x) #執行指令
conn.commit()
again = input("繼續輸入y/n?") #是否要繼續
if again[0].lower() == "n": #如果使用者輸入n則跳出迴圈
break
conn.close()

Query查詢資料

import sqlite3
conn = sqlite3.connect("myData.db")
results = conn.execute("SELECT * FROM students")
for record in results:
print("id:",record[0])
print("name:",record[1])
print("gender:",record[2])
conn.close()

import sqlite3
conn = sqlite3.connect("myData.db")
results = conn.execute("SELECT * FROM students")
allstudents = results.fetchall() #將資料轉成tuple
for s in allstudents:
print(s) #每個student都是一個tuple (1, 'peter', 'm')
conn.close()

Update更新資料

import sqlite3
conn = sqlite3.connect("myData.db")
sql = "UPDATE students SET name='james' WHERE id=1"
result = conn.execute(sql)
conn.commit()
conn.close()

Delete刪除資料

import sqlite3
conn = sqlite3.connect("myData.db")
sql = "DELETE FROM students WHERE id=1"
result = conn.execute(sql)
conn.commit()
conn.close()