操作SQLite
SQLite简介
SQLite数据类型
- intger: 整型
- VARCHAR(n): 长度不固定且其最大长度为 n 的字串,n不能超过 4000。
- CHAR(n): 长度固定为n的字串,n不能超过 254。
- real : 所有值都是浮动的数值,被存储为8字节的IEEE浮动标记序号.
- text: 值为文本字符串,使用数据库编码存储(TUTF-8, UTF-16BE or UTF-16-LE).
- blob: 值是BLOB数据块,以输入的数据格式进行存储。如何输入就如何存储,不改 变格式。
- Null 空
建立SQLite连接
import sqlite3
# 连接对象
conn = sqlite3.connect('db\\addressbook.db')
使用游标对象
# 游标 cursor
c = conn.cursor()
#
sql = "select * from LinkMan"
# 执行
result = c.execute(sql)
for row in result:
print(row)
使用游标后像数据库提交修改
sql = "insert into LinkMan values ('marry', '1234124', '1983-03-01', 1)"
# 增删改后提交
c.execute(sql)
conn.commit()
conn.close()
参数化查询
使用元祖
# 参数化查询 tuple
name = ("tom",)
sql = "select * from LinkMan Name= ?"
c.execute(sql, name)
conn.commit()
conn.close()
使用字典表
sql = "insert into LinkMan value (:name,:mobile,:birthday,:isvalid)"
# 这里的键名不是数据库的键名
c.execute(sql, {'name': 'john', 'mobile': '123415', 'birthday': '1999-1-1', 'isvalid': 1})
conn.commit()
conn.close()
避免使用.format() 方法参数化sql 语句,防止恶意注入。