python操作sqlite

pythopen 9年前發布 | 4K 次閱讀 Python

python2.5以上版本已經集成了sqlite模塊,下面是一些基本用法

#!/usr/bin/python

-- coding: iso-8859-1 --

from sqlite3 import dbapi2 as sqlite

Create a database:

con = sqlite.connect('mydatabase.db3') cur = con.cursor()

Create a table:

cur.execute('create table clients (id INT PRIMARY KEY, name CHAR(60))')

Insert a single line:

client = (5,"John Smith") cur.execute("insert into clients (id, name) values (?, ?)", client ) con.commit()

Insert several lines at once:

clients = [ (7,"Ella Fitzgerald"), (8,"Louis Armstrong"), (9,"Miles Davis") ] cur.executemany("insert into clients (id, name) values (?, ?)", clients ) con.commit()

cur.close() con.close()

下面的代碼對數據庫進行連接查詢

!/usr/bin/python

-- coding: iso-8859-1 --

from sqlite3 import dbapi2 as sqlite

Connect to an existing database

con = sqlite.connect('mydatabase.db3') cur = con.cursor()

Get row by row

print "Row by row:" cur.execute('select id, name from clients order by name;') row = cur.fetchone() while row: print row row = cur.fetchone()

Get all rows at once:

print "All rows at once:" cur.execute('select id, name from clients order by name;') print cur.fetchall()

cur.close() con.close() </pre>

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