python

python使用sqlite

2020-01-07  本文已影响0人  redher

前言

python通过sqlite3模块来操作sqlite。sqlite3是python的一个标准库并不需要安装,sqlite3是一个SQLite数据库DB-API2.0接口模块。

建立连接

要想使用这个模块,必须先创建一个Connection对象, 它代表数据库。

import sqlite3 
conn = sqlite3.connect('example.db')

上面的例子中,数据将存储在example.db文件中,如果文件存在则打开文件,如果文件不存在将新建一个example.db数据库文件,你也可以通过sqlite3.connect(":memory:")来创建一个内存中的数据库,通常情况下这没啥意义。

connect函数详解

函数签名:

sqlite3.connect(database[,timeout,detect_types,isolation_level,check_same_thread,factory,cached_statements,uri])

其返回的是一个Connection对象。

使用连接

当有了一个Connection对象后,你就可以创建Cursor游标对象,通过游标对象你就可以对整个数据库进行增删改查了。

c = conn.cursor()
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")
conn.commit()
conn.close()

让我们来逐一解释上面的语句:

我们通常的使用流程就是这样的。

Connection对象

属性:

Cursor对象

In [1]: import sqlite3
In [2]: con = sqlite3.connect('example.db')
In [3]: data = '2018-01-08'
In [4]: trans = 'BUY'
In [5]: symbol = 'RHAT'
In [6]: qty = '120'
In [7]: price = '12.1'
In [8]: cur = con.cursor()
In [9]: cur.execute('insert into stocks values (?,?,?,?,?)',(data,trans,symbol,qty,price))
Out[9]: <sqlite3.Cursor at 0x233f51c1e30>
In [10]: con.commit()
In [16]: cur.execute('select * from stocks where date=:data and trans=:buy',{'data':data,'buy':trans})
Out[16]: <sqlite3.Cursor at 0x233f51c1e30>
In [17]: print(cur.fetchone())
('2018-01-08', 'BUY', 'RHAT', 120.0, 12.1)
In [18]: cur.execute('select * from stocks')
Out[18]: <sqlite3.Cursor at 0x233f51c1e30>
In [19]: cur.fetchone()
Out[19]: ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
In [20]: cur.fetchone()
Out[20]: ('2006-01-05', 'BUY', 'CHE', 200.0, 1.2)
In [21]: cur.fetchone()
Out[21]: ('2018-01-08', 'BUY', 'RHAT', 120.0, 12.1)
In [22]: cur.fetchone()
In [23]: cur.execute('select * from stocks')
Out[23]: <sqlite3.Cursor at 0x233f51c1e30>
In [24]: cur.fetchone()
Out[24]: ('2006-01-05', 'BUY', 'RHAT', 100.0, 35.14)
In [25]: cur.fetchall()
Out[25]:
[('2006-01-05', 'BUY', 'CHE', 200.0, 1.2),
 ('2018-01-08', 'BUY', 'RHAT', 120.0, 12.1)]

SQLite与python类型

SQLite原生支持一下类型:NULL INTEGER REAL TEXT BLOB
这五种类型对应于python中的None int float str bytes,也就是说将这些类型发送给SQLite不会出现任何问题。而且sqlite3模块默认也是这么转换的。

上一篇 下一篇

猜你喜欢

热点阅读