2022年11月18日 星期五

Python SQLite資料庫操作簡介

 Python SQLite資料庫操作簡介

源自於 https://nkust.gitbook.io/python/sqlite-liao-cao-zuo-jie

Keyin_Data.py

import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
print("=========學生成績表輸入============")
print("===============================")
num = int(input('要輸入學生成績的筆數-->')) 
while (num>0):
    stuno = input("學號:")
    chi = input("國文成績:")
    eng = input("英文成績:")
    mat = input("數學成績:")
    his = input("歷史成績:")
    geo = input("地理成績:")
    sql_str = "insert into score(stuno, chi, eng, mat, his, geo) values('{}',{},{},{},{},{});".format(stuno, chi, eng, mat, his, geo)
    conn.execute(sql_str)
    conn.commit()
    num=num-1
conn.close()

Show_score.py
#顯示學生成績表
import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
rows = conn.execute("select * from score;")
for row in rows:
    for field in row:
        print("{}\t".format(field), end="")
    print()
conn.close()

>>> %Run show_score.py
1 A23001 89 98 34 55 67
2 A23002 89 85 78 65 96
3 A23003 98 95 92 93 85
4 A23004 56 65 85 75 64
5 A23005 96 86 75 74 84
6 A23006 56 54 52 85 90
7 A23007 85 76 96 91 90
8 A23008 63 65 67 68 64
9 A23009 45 78 89 92 62
10 A23010 86 87 84 85 80
11 A23011 65 96 68 67 60
>>
show2_score.py

import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("select * from score;")
rows = cur.fetchall()
print(rows[0].keys())
print(type(rows))
print(type(rows[0]))
print("學號\t國文\t英文")
for row in rows:
    print("{}\t{}\t{}".format(row['stuno'], row['chi'], row['eng']))

>>> %Run show2_score.py
['id', 'stuno', 'chi', 'eng', 'mat', 'his', 'geo']
<class 'list'>
<class 'sqlite3.Row'>
學號 國文 英文
A23001 89 98
A23002 89 85
A23003 98 95
A23004 56 65
A23005 96 86
A23006 56 54
A23007 85 76
A23008 63 65
A23009 45 78
A23010 86 87
A23011 65 96
>>> 






不需要安裝額外的資料庫管理程式或伺服器,只要一個檔案就可以使用的資料庫系統SQLite,是初學者和小型資料庫應用程式的最佳選擇,儘管嚴格來說它其實還不算是一個資料庫管理系統。
SQLite是一個以檔案為基礎的非常精簡版的SQL資料庫管理系統,它的最主要特色是沒有外部的伺服器系統或是執行中的對應程式,所有的操作都內嵌在操作資料庫的應用程式中(也就是我們編寫的程式),對於Python來說,只要載入對應的模組即可立即上手使用。
建立資料庫可以在程式中以create table指令完成,也可以透過圖形化的介面操作,在此使用後者,請先到以下的網站下載並安裝DB Browser for SQLite:
執行的畫面如下:
請在該介面中建立所需要的資料庫和資料表以供後續使用。建立完成之後的畫面如下所示:
也可以在此介面新增或編輯資料:
接下來就可以使用以下的程式碼來存取資料庫內容:
#顯示學生成績表
import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
rows = conn.execute("select * from score;")
for row in rows:
for field in row:
print("{}\t".format(field), end="")
print()
conn.close()
在Python中操作SQLite資料庫的標準步驟如下:
  1. 1.
    import sqlite3
  2. 2.
    使用sqlite3.connect("資料庫檔案路徑"),它會傳回一個指標,習慣上會使用conn這個變數來接收它。
  3. 3.
    利用前面所傳回的變數conn呼叫execute函數,函數中的內容就是SQL指令的字串。在execute執行之後,會傳回一個叫做Cursor的物件,它可以用來存取每一筆紀錄,也就是資料表中查詢結果的指標,由於會以列的型式來存取,因此習慣上在程式中會用rows或是cursor或是c這個變數來接收,在此程式例中是以rows來接收。
  4. 4.
    接著,可以使用迴圈的方式把每一列找出來使用。
在上述的程式中,取出的rows就是查詢結果的所有紀錄,以列的型式來存放,而由於每一列中有許多的欄位(field),所以在上面的程式中使用了2層的迴圈,外層迴圈用來找出每一列,內層迴圈用來找出列中的每一欄。
1 A23001 80 98 34 55 67
2 A23002 89 99 45 89 90
3 A23003 89 90 87 88 90
4 A23004 99 89 90 99 100
5 A23005 89 56 88 90 52
輸入成績並把它們儲存入資料庫的標準作法:
import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
stuno = input("學號:")
chi = input("國文成績:")
eng = input("英文成績:")
mat = input("數學成績:")
his = input("歷史成績:")
geo = input("地理成績:")
sql_str = "insert into score(stuno, chi, eng, mat, his, geo) values('{}',{},{},{},{},{});".format(stuno, chi, eng, mat, his, geo)
conn.execute(sql_str)
conn.commit()
conn.close()
設定以欄位名稱操作資料庫的程式設計標準步驟:
import sqlite3
dbfile = "school.db"
conn = sqlite3.connect(dbfile)
conn.row_factory = sqlite3.Row
cur = conn.cursor()
cur.execute("select * from score;")
rows = cur.fetchall()
print(rows[0].keys())
print(type(rows))
print(type(rows[0]))
print("學號\t國文\t英文")
for row in rows:
print("{}\t{}\t{}".format(row['stuno'], row['chi'], row['eng'

沒有留言:

張貼留言

2024產專班 作業2 (純模擬)

2024產專班 作業2  (純模擬) 1) LED ON,OFF,TIMER,FLASH 模擬 (switch 控制) 2)RFID卡號模擬 (buttom  模擬RFID UID(不從ESP32) Node-Red 程式 [{"id":"d8886...