標籤:遊標 hal key python close sqlite資料庫 插入資料 建立 tps
1.資料庫操作步驟
使用sqlite3需要匯入包sqlite3,資料庫在操作時需要先串連資料庫,然後建立遊標Cursor。
當程式運行完以後,需要先關閉遊標,然後再關閉資料庫。
(1)查詢操作
查詢操作的步驟為:1.使用SQL語句進行查詢,2.從fetchall中將查詢結果讀出
使用Cursor對象執行select語句時,通過featchall()可以拿到結果集。結果集是一個list,每個元素都是一個tuple,對應一行記錄。
範例程式碼如下
import sqlite3#匯入包conn=sqlite3.connect(‘sample_database‘)#串連到SQLite資料庫cursor=conn.cursor()#建立一個Cursorcursor.execute("select employee.firstname,employee.lastname from employee")#使用SQL語句對資料庫進行操作for row in cursor.fetchall():#從fetchall中讀取操作 print(row)cursor.close()#關閉Cursorconn.close()#關閉資料庫(2)插入、刪除與更新操作
步驟為:1.使用SQL語句進行查詢,2.提交操作
import sqlite3conn=sqlite3.connect(‘sample_database‘)#串連到SQLite資料庫cursor=conn.cursor()#建立一個Cursorcursor.execute(‘create table user (id varchar(20) primary key, name varchar(20))‘)#用SQL語句建立一個表cursor.execute(‘insert into user (id, name) values (\‘1\‘, \‘Michael\‘)‘)#用SQL語句向表中插入資料print(cursor.rowcount)#顯示插入的函數cursor.close()#關閉Cursorconn.commit()#提交操作conn.close()#關閉資料庫
使用Cursor對象執行insert,update,delete語句時,執行結果由rowcount返回影響的行數,就可以拿到執行結果
參考資料
使用SQLite-廖雪峰:https://www.liaoxuefeng.com/wiki/001374738125095c955c1e6d8bb493182103fac9270762a000/001388320596292f925f46d56ef4c80a1c9d8e47e2d5711000
Sqlite3資料庫Python基礎操作