第一節:數據庫API與全局變量及核心類基本流程
第二節:案例實操-動態創建數據表
import sqlite3# 1 打開數據庫鏈接# SQLite是一個沒有后臺進程的數據庫,磁盤上的一個文件就可以對應SQLite數據庫conn = sqlite3.connect('test.db')# 2 打開游標c = conn.cursor()# 3 使用游標的execute方法執行任意的SQL語句(DDL)c.execute(''' craete table user_tb( _id integer primary key autoincrement, name text, pass text, age interger)''')c.execute(''' craete table order_tb( _id integer primary key autoincrement, item_name text, item_price real, item_number integer, user_id integer, foreign key(user_id) references user_tb(_id))''')# 4 關閉游標c.close()# 5 關閉數據庫鏈接conn.colse()
第三節:使用SQLite Expert
第四節:執行DML語句
import sqlite3# 創建數據庫conn = sqlite3.connect('test.db')# 獲取游標c = conn.cursor()# 執行SQL語句# 插入insert into tabnamec.execute('insert into user_tb values(null, ?, ?, ?)', ('fkjava', '33445', 23))c.execute('insert into user_tb values(null, ?, ?, ?)', ('crazyit', '35555', 25))c.execute('insert into order_tb values(null, ?, ?, ?, ?)', ('鼠標', 33, 3, 1))# 更新 update tabnamec.execute('update user_tb set pass=?', ('98765',))# 執行完DML語句之后,如果程序獲取被DML語句修改的記錄條數,可通過游標的rowcount來獲取print('受影響的記錄條數:' , c.rowcount)# 提交事務,使修改生效conn.commit()# 關閉資源c.close()conn.close()
第五節:執行查詢
import sqlite3# 創建數據庫conn = sqlite3.connect('test.db')# 獲取游標c = conn.cursor()# 執行SQL語句c.execute('select * from user_td where _id > ?', (2,))# 所有查詢結果都通過游標來獲取# description屬性(元組)返回列信息# 如果要獲取查詢數據,fetchxxx或者直接迭代游標for col in c.description: print(col[0], end='\t')print() #--------------------fetchone方法------------------ while True: # 用fetchone每次獲取一條記錄 row = c.fetchone() # 如果row為空,說明沒有數據 if not row: break else: # 輸出該行內各個單元格的數據 for d in row: print(col[0], end='\t') print()#--------------------游標當成可迭代對象------------------ for row in c: # 輸出該行內各個單元格的數據 for d in row: print(col[0], end='\t') print()# 關閉資源c.close()conn.close() 第六節:案例實操-使用事務控制數據庫操作
第七節:案例實操-用程序執行SQL腳本
insert into user_tb values(null, '張三', '11111', 23)insert into user_tb values(null, '李四', '22222', 24)insert into user_tb values(null, '小吳', '33333', 25)creat table test_td(_id integer primary key autoincrement,name text,pass text,description);creat table emp_td(_id integer primary key autoincrement,emp_name,emp_pass,emp_title);
import sqlite3# 創建數據庫conn = sqlite3.connect('test.db')# 打卡SQL腳本所在的文件with open('a.sql', 'r', True, 'UTF-8') as f: # 讀取文件中的SQL語句 sql = f.read() # 直接用數據庫連接對象來執行SQL腳本 c.executescript(sql) # 提交事務conn.commit() # 關閉資源conn.close() |
|
來自: copy_left > 《python相關》