python学习笔记32:操作sqlite数据库

import sqlite3

# 1. 创建数据库连接
#   如果test.db存在, 则建立连接, 返回connect对象
#   如果test.db不存在, 则新建数据库, 再建立连接, 返回connect对象
conn = sqlite3.connect(database='test.db')

# 2. 创建cursor对象
cursor = conn.cursor()

# 3. 执行sql指令
# -- select语句, 返回内容, 需要通过fetchall()来获取, 返回内容为一个list, list元素为单个记录(单个记录是一个tuple, 元素为各个value)
list_record = cursor.execute('''
    SELECT * FROM student;
''').fetchall()

# -- update语句, 不返回内容, 不需要fetchall()
cursor.execute('''
    UPDATE student SET yuwen=60, shuxue=59
    WHERE name=gou AND age=15;
''')


# 4. 关闭cursor对象
cursor.close()

# 5. 提交事务
conn.commit()

# 6. 关闭数据库连接
conn.close()

posted @ 2023-05-22 14:31  编程驴子  阅读(18)  评论(0编辑  收藏  举报