Python連線SQLite資料庫

2021-08-09 18:58:23 字數 2786 閱讀 4146

sqlite作為一款輕型資料庫,管理工具有很多,比如sqlite expert professional,很適合用來儲存python**,爬蟲的相關資料,下面列出基本的增刪查改操作

讀取操作:

conn1 =sqlite3.connect(board.databasepath)

conn1.row_factory =sqlite3.row

conn1.execute(

"pragma foreign_key=on")

c1 =conn1.cursor()

try:

#執行查詢操作

c1.execute("

\select username as username \

from \

register \

where name=?;

", \

(username,))

#異常處理

except

(sqlite3.databaseerror) as e:

print

e

return

none

else

: user_row =c1.fetchone()

#呼叫資料

finally

: conn1.close()

#關閉連線

增加資料:

conn =sqlite3.connect(board.databasepath)

conn.row_factory =sqlite3.row

conn.execute(

"pragma foreign_key=on")

c =conn.cursor()

md5 =hashlib.md5()

md5.update(password)

encrypted_passwd =md5.hexdigest()

try:

#增加資料

c.execute("

\ insert into register (name,work,email,username,password) values (?,?,?,?,?);

", \

(name, workplace, email, username, encrypted_passwd))

c.execute(

"select last_insert_rowid() as user_id from register;")

except

(sqlite3.databaseerror) as e:

print

e conn.rollback()

return

false

else

: conn.commit()

return

true

finally

: conn.close()

刪除操作:

conn=sqlite3.connect(board.databasepath)

conn.execute(

"pragma foreign_key=on")

conn.row_factory=sqlite3.row

c=conn.cursor()

try:

c.execute("\

delete from setting where key=? and parent_id=?;",\

(self.slick.key,self.id))

except

(sqlite3.databaseerror) as e:

print

e conn.rollback()

return

false

else

: conn.commit()

self.slick.items.pop(self.id)

self=none

return

true

finally

: conn.close()

修改操作:

conn=sqlite3.connect(board.databasepath)

conn.execute(

"pragma foreign_key=on")

conn.row_factory=sqlite3.row

c=conn.cursor()

try:

c.execute("\

update setting set value=? where key=? and name=?;",\

(self.title,self.key,

"jumbotron_title"))

c.execute("\

update setting set value=? where key=? and name=?;",\

(self.content,self.key,

"jumbotron_content"))

except

(sqlite3.databaseerror) as e:

print

e conn.rollback()

return

false

else

: conn.commit()

return

true

finally

: conn.close()

python 連線sqlite及操作

import sqlite3 查詢def load table 連線資料庫 con sqlite3.connect e datebase sqlitestudio park.db 獲得游標 cur con.cursor 查詢整個表 cur.execute select from table list...

Python連線SQLite資料庫

python 3.7.4 sqlite3def init self,path 建構函式 資料庫路徑path,若存在資料庫則連線,否則建立.db檔案 連線到指定資料庫 self.connect sqlite3.connect path self.cursor self.connect.cursor 初...

Python與SQLite和MYSQL資料庫

python內建了sqlite模組並可以方便的連線各種資料庫。sqlite是乙個輕量級資料庫乙個資料庫例項就是乙個檔案,可以方便的整合到各種應用程式中。python內建sqlite3模組,無需任何配置即可使用。import sqlite3 connect db,create if not exist...