python3 sqlite 使用
2018-01-21 00:00
190 查看
SQLlte数据类型
SQLite能保存什么样的数据类型 ?? 可以保存空值、整数、浮点数、字符串和blob。 什么是blob ?? 是二进制大对象。例如图片、音乐、zip文件。 什么是游标 ?? 游标是在数据库中用来移动和执行查询的对象。 SQL的全部知识呢??? 远不止这些网站 http://www.runoob.com/sql/sql-tutorial.html 有一个很好的初学教程
创建数据库,创建表
执行语句后一定要提交!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!如果要使用SQL必须要导入sqlite3库。
import sqlite3 # '''创建一个数据库,文件名''' conn = sqlite3.connect('./mytest1.db') # '''创建游标''' cursor = conn.cursor() # '''执行语句''' sql = '''create table students ( name text, username text, id int)''' cursor.execute(sql) # '''使用游标关闭数据库的链接''' cursor.close()
添加数据
要添加一些数据到表中,需要使用insert命令和一些特殊的格式。import sqlite3 conn = sqlite3.connect('mytest.db') cursor = conn.cursor() print('hello SQL') while True: name = input('student\'s name') username = input('student\'s username') id_num = input('student\'s id number:') # '''insert语句 把一个新的行插入到表中''' sql = ''' insert into students (name, username, id) values (:st_name, :st_username, :id_num)''' # 把数据保存到name username和 id_num中 cursor.execute(sql,{'st_name':name, 'st_username':username, 'id_num':id_num}) conn.commit() cont = ('Another student? ') if cont[0].lower() == 'n': break cursor.close()
查询数据
(*) 告诉数据库给出所有内容。
code:
import sqlite3 import os os.chdir('d:\\pycharm\\lesson\\sn01') # conn = sqlite3.connect('D:\\pycharm\\lesson\\sn01\\SQL\\mytest.db') conn = sqlite3.connect(r'./SQL/mytest.db') cursor = conn.cursor() # 查询所有的学生表 # sql = '''select * from students''' ''' 得到数据库中的名字''' sql = "select rowid, username from students" # 执行语句 results = cursor.execute(sql) # 遍历打印输出 all_students = results.fetchall() for student in all_students: print(student)
1. 使用大量操作
如果你需要在数据库中一次性插入很多行,那么你真不应该使用 execute。sqlite3 模块提供了批量插入的方式:executemany。而不是像这样做:
for row in iter_data():
connection.execute('INSERT INTO my
3ff0
_table VALUES (?)', row)
你可以利用这个事实,即 executemany 接受元组的生成器作为参数:
connection.executemany(
'INSERT INTO my_table VALUE (?)',
iter_data()
)
这不仅更简洁,而且更高效。实际上,sqlite3 在幕后利用 executemany 实现 execute,但后者插入一行而不是多行。
我写了一个小的基准测试,将一百万行插入空表(数据库在内存中):
executemany: 1.6 秒
execute: 2.7 秒
2. 你不需要游标
一开始我经常搞混的事情就是,光标管理。在线示例和文档中通常如下:
connection = sqlite3.connect(':memory:')
cursor = connection.cursor()
# Do something with cursor
但大多数情况下,你根本不需要光标,你可以直接使用连接对象(本文末尾会提到)。像execute和executemany类似的操作可以直接在连接上调用。以下是一个证明此事的示例:
import sqlite3
connection = sqlite3(':memory:')
# Create a table
connection.execute('CREATE TABLE events(ts, msg)')
# Insert values
connection.executemany(
'INSERT INTO events VALUES (?,?)',
[
(1, 'foo'),
(2, 'bar'),
(3, 'baz')
]
)
# Print inserted rows
for row in connnection.execute('SELECT * FROM events'):
print(row)
3. 光标(Cursor)可被用于迭代
你可能经常会看到使用fetchone或fetchall来处理SELECT查询结果的示例。但是我发现处理这些结果的最自然的方式是直接在光标上迭代:
for row in connection.execute('SELECT * FROM events'):
print(row)
这样一来,只要你得到足够的结果,你就可以终止查询,并且不会引起资源浪费。当然,如果事先知道你需要多少结果,可以改用LIMIT SQL语句,但Python生成器是非常方便的,可以让你将数据生成与数据消耗分离。
4. 使用Context Managers(上下文管理器)
即使在处理SQL事务的中间,也会发生讨厌的事情。为了避免手动处理回滚或提交,你可以简单地使用连接对象作为上下文管理器。 在以下示例中,我们创建了一个表,并错误地插入了重复的值:
import sqlite3
connection = sqlite3.connect(':memory:')
with connection:
connection.execute(
'CREATE TABLE events(ts, msg, PRIMARY KEY(ts, msg))')
try:
with connection:
connection.executemany('INSERT INTO events VALUES (?, ?)', [
(1, 'foo'),
(2, 'bar'),
(3, 'baz'),
(1, 'foo'),
])
except (sqlite3.OperationalError, sqlite3.IntegrityError) as e:
print('Could not complete operation:', e)
# No row was inserted because transaction failed
for row in connection.execute('SELECT * FROM events'):
print(row)
connection.close()
5. 使用Pragmas
…当它真的有用时在你的程序中有几个 pragma 可用于调整 sqlite3 的行为。特别地,其中一个可以改善性能的是synchronous:
connection.execute('PRAGMA synchronous = OFF')
你应该知道这可能是危险的。如果应用程序在事务中间意外崩溃,数据库可能会处于不一致的状态。所以请小心使用! 但是如果你要更快地插入很多行,那么这可能是一个选择。
6. 推迟索引创建
假设你需要在数据库上创建几个索引,而你需要在插入很多行的同时创建索引。把索引的创建推迟到所有行的插入之后可以导致实质性的性能改善。
7. 使用占位符插入 Python 值
使用 Python 字符串操作将值包含到查询中是很方便的。但是这样做非常不安全,而 sqlite3 给你提供了更好的方法来做到这一点:
# Do not do this!
my_timestamp = 1
c.execute("SELECT * FROM events WHERE ts = '%s'" % my_timestamp)
# Do this instead
my_timestamp = (1,)
c.execute('SELECT * FROM events WHERE ts = ?', my_timestamp)
此外,使用Python%s(或格式或格式的字符串常量)的字符串插值对于executemany来说并不是总是可行。所以在此尝试没有什么真正意义!
相关文章推荐
- python之sqlite3使用详解
- Python SQLite的使用经验
- python之sqlite3使用详解
- python 在linux中使用sqlite3
- 如何在python中使用sqlite3
- 使用python将Sqlite中的数据直接输出为CVS
- python之sqlite3使用详解
- python之sqlite3使用详解
- python之sqlite3使用详解
- python之sqlite3使用详解
- python使用sqlite
- python系列学习七——使用sqlite管理数据
- python之sqlite3使用详解
- python之sqlite3使用详解(转)
- python之sqlite3使用详解
- python之sqlite3使用详解
- python之sqlite3使用详解
- python之sqlite3使用详解
- python之sqlite3使用详解
- Python中Sqlite的使用&ORM的使用&如何通过code初始化DB