Python-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)
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值