sqlite3模块学习
Sqlite3
1 导入模块
import sqlite3
2 模块使用
2.1 创建连接
_co = sqlite3.connect('./test.db')
使用sqlite3的connect
函数可以创建数据库或连接数据库。
如果数据库存在,连接数据库。
如果数据库不存在,创建数据库。
传入的参数为:数据库名。
2.2 创建游标
连接到数据库后,需要创建游标
对象,它是用于执行SQL查询语句并与数据库交互的对象。
conn.cursor()
2.3 创建数据表
创建数据表来存储数据
def create_database():
cur = _co.cursor()
try:
cur.execute("""
CREATE TABLE student(
id integer primary key autoincrement,
name text not null,
age integer not null,
gender char(10) not null default('male')
);
""")
finally:
cur.close()
2.4 查询数据
查询多列数据
def select_multi_col():
cur = _co.cursor()
try:
cur.execute("SELECT id, name, age, gender FROM student")
print(cur.fetchall())
finally:
cur.close()
查询单列数据
def select_one_col():
cur = _co.cursor()
try:
cur.execute("SELECT name FROM student WHERE gender = 'male'")
print(cur.fetchone())
# print(cur.fetchall())
finally:
cur.close()
2.5 插入数据
插入单条数据
def insert_one(stu):
cur = _co.cursor()
try:
cur.execute("INSERT INTO student(name, age, gender) values(?, ?, ?)", stu)
_co.commit()
finally:
cur.close()
插入多条数据
def insert_multi(stu: list):
cur = _co.cursor()
try:
cur.executemany("INSERT INTO student(name, age, gender) values(?, ?, ?)", stu)
_co.commit()
finally:
cur.close()
2.6 修改数据
修改单条数据
def modify_one(condition):
cur = _co.cursor()
try:
cur.execute("UPDATE student SET name = ? WHERE age = ?", condition)
_co.commit()
finally:
cur.close()
修改多条数据
def modify_multi(condition):
cur = _co.cursor()
try:
cur.executemany("UPDATE student SET name = ? WHERE age = ?", condition)
_co.commit()
finally:
cur.close()
2.7 删除数据
删除单条数据
def delete_one(condition):
cur = _co.cursor()
try:
cur.execute("DELETE FROM student WHERE age = ?", condition)
_co.commit()
finally:
cur.close()
删除多条数据
def delete_multi(condition):
cur = _co.cursor()
try:
cur.executemany("DELETE FROM student WHERE gender = ?", condition)
_co.commit()
finally:
cur.close()
2.8 注意事项
2.8.1 传参
- 多个占位符传参
- 单条
- (a, b, c)
- 多条
- 格式一: [(a, )]
- 格式二: ((a, ), )
- 单条
- 单个占位符传参
- 单条
- (a, )
- 多条
- (a, b, c)
- 单条
2.8.2 查询数据判空
- cur.fetchone()
if cur.fetchone() is None:
print(1)
- cur.fetchall()
if len(cur.fetchall()) == 0:
print(1)