利用python語言連接數據庫

①去https://sqlitebrowser.org/下載DB Browser for SQLite

②利用python語言創建數據庫連線
#ch29_3.py
import sqlite3
conn = sqlite3.connect(“myInfo.db”) # 資料庫連線
sql = ‘’‘Create table students(
id int,
name text,
gender text
score int)’’’
conn.execute(sql) # 執行SQL指令
conn.close() # 關閉資料庫連線
③將所創建數據庫中的每一欄填入數據

ch29_4.py

import sqlite3
conn = sqlite3.connect(“myInfo.db”) # 資料庫連線
print(“請輸入myInfo資料庫students表單資料”)
while True:
new_id = int(input("請輸入id : ")) # 轉成整數
new_name = input("請輸入name : ")
new_gender = input("請輸入gender : ")
new_score = input("請輸入score : ")
x = (new_id, new_name, new_gender, new_score)
sql = ‘’‘insert into students values(?,?,?,?)’’’
conn.execute(sql,x)
conn.commit() # 更新資料庫
again = input("繼續(y/n)? ")
if again[0].lower() == “n”:
break
conn.close()
④運行結果顯示如下:
在這裏插入圖片描述在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章