Python使用sqlite3運算元據庫

2021-07-10 18:41:20 字數 842 閱讀 6591

1、首先通過執行sql語句建立一張表

先建立一張字尾是.sql的檔案,裡面輸入sql建立表的語句,如下所示

drop table if exists entries;

create table entries(

id integer primary key autoincrement,

title text not null,

text text not null);

2、在python中通過sqlite3完成建立**

如下是建立**進行的簡單的插入資料和讀取操作

import sqlite3

#connect db

db = sqlite3.connect('schema.db')

#open sql

f=open('schema.sql','r')

#create table

db.cursor().executescript(f.read())

#insert

db.execute('insert into entries (title, text) values(?,?)',['jack','mao'])

#read table

cur = db.execute('select title, text from entries order by id desc')

entries = [dict(title=row[0],text=row[1]) for row in cur.fetchall()]

print(entries)

f.close()

db.close()

使用sqlite3 模組操作sqlite3資料庫

python內建了sqlite3模組,可以操作流行的嵌入式資料庫sqlite3。如果看了我前面的使用 pymysql 操作mysql資料庫這篇文章就更簡單了。因為它們都遵循pep 249,所以操作方法幾乎相同。廢話就不多說了,直接看 吧。都差不多,首先匯入模組,然後建立連線,然後獲取游標物件,之後利...

python之sqlite3使用詳解

如果該資料庫操作不需要返回結果,就直接用conn.execute查詢,根據資料庫事務隔離級別的不同,可能修改資料庫需要conn.commit 如果需要返回查詢結果則用conn.cursor建立游標物件cur,通過cur.execute查詢資料庫,用cur.fetchall cur.fetchone ...

python之sqlite3使用詳解

python sqlite資料庫是一款非常小巧的嵌入式開源資料庫軟體,也就是說沒有獨立的維護程序,所有的維護都來自於程式本身。它使用乙個檔案儲存整個資料庫,操作十分方便。它的最大優點是使用方便,功能相比於其它大型資料庫來說,確實有些差距。但是效能表現上,sqlite並不遜色。麻雀雖小,五臟俱全,sq...