pythonsqlite3 memory_python+sqlite3

这篇博客介绍了如何使用Python的sqlite3模块连接到内存数据库,包括创建表、插入数据和查询数据。作者提到了使用`:memory:`参数创建临时数据库,并讨论了处理中文字符时的注意事项,以及使用`u`前缀进行Unicode字符串操作的重要性。
摘要由CSDN通过智能技术生成

# -*- coding:utf-8 -*-

'''

Created on 2015年10月8日

(1.1)Python 2.7 Tutorial Pt 12 SQLite -

https://www.youtube.com/watch?v=Ll_ufNL5rDA

(1.2) sqlite3.connect(":memory:") 这个是亮点.

(1.3)

[Python] 74 Creating a database with SQLite 3 -

https://www.youtube.com/watch?v=n-Rtfd1Vv_M

db.row_factory = sqlite3.Row

在我电脑上,是否加上上面这句没什么影响.

(2.1)存储中文时,同样的必须加 u . 但是直接打印出来的是 \uxxxx 格式的内容

(2.2)如果不加 u ,报错如下:

sqlite3.ProgrammingError:

You must not use 8-bit bytestrings unless you use a text_factory

that can interpret 8-bit bytestrings (like text_factory = str).

It is highly recommended that you instead just switch your application to Unicode strings.

'''

import sqlite3

# con = sqlite3.connect("sample.db")

# con = sqlite3.connect(":memory:")

def main():

db = sqlite3.connect(":memory:")

db.row_factory = sqlite3.Row

db.execute("drop table if exists test")

db.execute("create table test (t1 text, i1 int)")

db.execute('insert into test (t1, i1) values(?,?)', (u'一', 1))

db.execute('insert into test (t1, i1) values(?,?)', ('two', 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 i1, t1 from test order by i1')

for row in cursor:

print(row)

db.close()

if __name__ == "__main__": main()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值