`
mingren135
  • 浏览: 69272 次
  • 性别: Icon_minigender_1
  • 来自: 上海
社区版块
存档分类
最新评论

Python-使用Sqlite

 
阅读更多

内嵌式数据库sqlite想必大家都听说过,Python内置了sqlite模块,提供了访问sqlite的统一标准。不同的Python版本带的sqlite版本不大一样,如果机器在Python环境中找不到sqlite3,则尝试导入sqlite2或sqlite模块试试。

 

我用到的机器安装的是Python 2.4.3 (#1, Jun 11 2009, 14:09:37),只能导入sqlite模块,使用方法上没有什么区别的。

 

以创建一张表,执行插入、查询、更新、删除为例,基本步骤如下:

 

1)创建数据库连接,如果aa.db文件不存在,则会自动新创建一个

 

conn = sqlite.connect('/home/admin/aa.db')

2)获取游标

 

cursor = conn.cursor()

3)创建表

 

cursor.execute("create table if not exists order_log(id integer primary key autoincrement, itemId varchar(20), orderId varchar(40),errorCode varchar(100))")

4)插入数据

 

cursor.execute('''insert into order_log values(null, '123456','2019888299934384','DUPLICATE ORDER')''')
cursor.execute('''insert into order_log values(null, '123457','2019888299934385','SESSION INVALIDA')''')

5)查询数据 

 

cursor.execute('select * from order_log')
result = cursor.fetchall()
print result
-------------
[(1, '123456', '2019888299934384', 'DUPLICATE ORDER'), (2, '123457', '2019888299934385', 'SESSION INVALIDA')]

6)更新数据 

 

cursor.execute("update order_log set itemId='888999' where id = 2")
#查询结果
----------------
[(1, '123456', '2019888299934384', 'DUPLICATE ORDER'), (2, '888999', '2019888299934385', 'SESSION INVALIDA')]

 7)删除数据

 

cursor.execute('delete from order_log where id=2')  
#查询数据  
-----------  
[(1, '123456', '2019888299934384', 'DUPLICATE ORDER')]  

cursor.execute('delete from order_log')  
#查询数据 
-----------
[]
 

8)关闭数据库

cursor.close()
conn.close()
 

9)其它

#连接内存数据库
conn = sqlite.connect(':memory')

#事务回滚
conn.rollback()
 

 

 

 

 

 

 

 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics