SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process and allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger database such as PostgreSQL or Oracle.-------摘自 官方文檔
1.簡單的建表
#!/usr/bin/python3
# databases.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
import sqlite3
def main():
db=sqlite3.connect('text.db')
db.execute('drop table if exists test')
db.execute('create table test (t1 text,i1 int)')
db.execute('insert into test (t1,i1) values(?,?)',('one',1))
db.execute('insert into test (t1,i1) values(?,?)',('tow',2))
db.execute('insert into test (t1,i1) values(?,?)',('three',3))
db.execute('insert into test (t1,i1) values(?,?)',('four',4))
db.commit()
cursor=db.execute('select * from test order by t1')
for row in cursor:
print(row)
if __name__ == "__main__": main()
('four', 4)
('one', 1)
('three', 3)
('tow', 2)
2.返回row對象 用row_factory
#!/usr/bin/python3
# databases.py by Bill Weinman [http://bw.org/]
# This is an exercise file from Python 3 Essential Training on lynda.com
# Copyright 2010 The BearHeart Group, LLC
import sqlite3
def main():
db=sqlite3.connect('text.db')
db.row_factory=sqlite3.Row #row factory 來決定行是怎麼返回的
db.execute('drop table if exists test')
db.execute('create table test (t1 text,i1 int)')
db.execute('insert into test (t1,i1) values(?,?)',('one',1))
db.execute('insert into test (t1,i1) values(?,?)',('tow',2))
db.execute('insert into test (t1,i1) values(?,?)',('three',3))
db.execute('insert into test (t1,i1) values(?,?)',('four',4))
db.commit()
cursor=db.execute('select * from test order by t1')
for row in cursor:
#print(dict(row)) #已字典的形式輸出返回的行 dict()構造方法
print(row['t1'],row['i1'])
if __name__ == "__main__": main()