1. 程式人生 > >Python連接SQLite數據庫

Python連接SQLite數據庫

ast items finally fin comm 連接 let 很多 sep

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數據庫