Python学习之sqlite3(1)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/nk_wang/article/details/85844262

SQLite 是一个软件库,实现了自给自足的、无服务器的、零配置的、事务性的 SQL 数据库引擎。SQLite 是在世界上最广泛部署的 SQL 数据库引擎。SQLite 源代码不受版权限制。
在Python中,SQLite作为一个内嵌模块使用,如何使用SQLite模块呢??

创建数据库

为了使用sqlite3数据库模块,首先得创建一个Connection对象代表数据库,下面创建一个数据库example.db。

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

创建表插入数据

一旦创建Connection对象后,需要创建Cursor对象,然后调用Cursor对象的execute()方法执行SQL语句。

c = conn.cursor()

# Create table
c.execute('''CREATE TABLE stocks
             (date text, trans text, symbol text, qty real, price real)''')

# Insert a row of data
c.execute("INSERT INTO stocks VALUES ('2006-01-05','BUY','RHAT',100,35.14)")

# Save (commit) the changes
conn.commit()

# We can also close the connection if we are done with it.
# Just be sure any changes have been committed or they will be lost.
conn.close()

查询插入的数据

刚才插入的数据通过Cursor对象执行SQL语句查询。

for row in c.execute('SELECT * FROM stocks ORDER BY price'):
        print(row)

输出结果如下所示:

('2006-01-05', 'BUY', 'RHAT', 100, 35.14)

猜你喜欢

转载自blog.csdn.net/nk_wang/article/details/85844262