Python DB sqlite3

来源:互联网 发布:西安研究所待遇 知乎 编辑:程序博客网 时间:2024/05/16 08:10

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()





0 0
原创粉丝点击