python 操作sqlite3数据库
#!/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()
execute中的数据库操作必须使用大写,不然无法辨识
本文由用户 jopen 自行上传分享,仅供网友学习交流。所有权归原作者,若您的权利被侵害,请联系管理员。
转载本站原创文章,请注明出处,并保留原始链接、图片水印。
本站是一个以用户分享为主的开源技术平台,欢迎各类分享!