python 操作sqlite3數據庫

jopen 10年前發布 | 29K 次閱讀 SQLite3 Python開發

#!/usr/bin/env python

coding:utf-8

import os import sqlite3

try: os.remove("test.db") except: pass

create/open the db

conn = sqlite3.connect("test.db") c = conn.cursor()

create the table in db

c.execute('''CREATE TABLE infors (id int primary key,sort int,name text)''')

c.execute('''CREATE TABLE book (id int primary key, sort int, name text, price real, infors int, FOREIGN KEY (infors) REFERENCES infors(id) )''')

insert into values in table

books = [(1, 1, 'Cook Recipe', 3.12, 1), (2, 3, 'Python Intro', 17.5, 2), (3, 2, 'OS Intro', 13.6, 2), ] c.execute("INSERT INTO infors VALUES (1,1,'kitchen')") c.execute("INSERT INTO infors VALUES (?,?,?)",(2,2,'computer')) c.executemany("INSERT INTO book VALUES (?,?,?,?,?)",books)

select * from table

c.execute('SELECT name FROM infors ORDER BY sort') print c.fetchone() print c.fetchone() print "**"

c.execute('SELECT * FROM book WHERE book.infors=1') print c.fetchall()

print "**"

for row in c.execute('SELECT name,price FROM book ORDER BY sort'): print row

update and delete

c.execute('UPDATE book SET price=? WHERE id=?',(1000, 1)) c.execute('DELETE FROM book WHERE id=2')

conn.commit() conn.close()</pre>

execute中的數據庫操作必須使用大寫,不然無法辨識

 本文由用戶 jopen 自行上傳分享,僅供網友學習交流。所有權歸原作者,若您的權利被侵害,請聯系管理員。
 轉載本站原創文章,請注明出處,并保留原始鏈接、圖片水印。
 本站是一個以用戶分享為主的開源技術平臺,歡迎各類分享!