Python DB sqlite3

本文将介绍Python中使用SQLite数据库的基本操作,包括简单的建表、插入数据、使用row_factory等高级特性,以及如何通过Python代码进行数据库交互。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值