python-sqlite3使用指南

python下sqlite3使用指南

开发环境

  • vscode

image-20230527145848272

  • 开发语言: python

vscode SQLite插件使用方法:

image-20230527150827970

之后在这里就可以发现可视化数据:

image-20230527150900168

sqlite3常用API

Python 2.5.x 以上版本默认自带了sqlite3 ,不需要下载,

要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection

连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。

# -*- coding: utf-8 -*-

import os, sqlite3

db_file = os.path.join(os.path.dirname(__file__), "test.db")
# if os.path.isfile(db_file):
#     os.remove(db_file)


def get_connect():
    return sqlite3.connect(db_file)


def insert_or_update(sql_str):
    con = get_connect()
    cursor = con.cursor()
    r = cursor.execute(sql_str)
    cursor.close()
    con.commit()
    con.close()
    return r


def add_user():
    insert_or_update("INSERT INTO  user (id,name,score) VALUES('1','a',1)")
    insert_or_update("INSERT INTO  user (id,name,score) VALUES('2','b',1)")
    insert_or_update("INSERT INTO  user (id,name,score) VALUES('3','c',1)")
    insert_or_update("INSERT INTO  user (id,name,score) VALUES('4','d',1)")


def update_user():
    insert_or_update("UPDATE  user set score=999 where id = 1")
    insert_or_update("UPDATE  user set score=999 where id = 2")
    insert_or_update("UPDATE  user set score=999 where id = 3")
    insert_or_update("UPDATE  user set score=999 where id = 4")


def select(cmd):
    con = get_connect()
    cur = con.cursor()
    result = cur.execute(cmd)
    return result.fetchall() ,con

# add_user()
# update_user()

# r, c = select("select * from user")
# print(r)
# c.close()

CRUD实例

import sqlite3  
  
# 连接到数据库  
conn = sqlite3.connect('example.db')  
  
# 创建一个游标对象  
cur = conn.cursor()  
  
# 创建一个名为example_table的表  
cur.execute('''CREATE TABLE example_table (id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')  
  
# 插入数据  
cur.execute("INSERT INTO example_table (name, age) VALUES ('Alice', 25)")  
cur.execute("INSERT INTO example_table (name, age) VALUES ('Bob', 30)")  
cur.execute("INSERT INTO example_table (name, age) VALUES ('Charlie', 35)")  
  
# 提交更改  
conn.commit()  
  
# 查询数据  
cur.execute("SELECT * FROM example_table")  
for row in cur.fetchall():  
    print(row)  
  
# 更新数据  
cur.execute("UPDATE example_table SET age = 40 WHERE name = 'Bob'")  
conn.commit()  
  
# 删除数据  
cur.execute("DELETE FROM example_table WHERE name = 'Charlie'")  
conn.commit()  
  
# 关闭连接  
conn.close()

此代码示例首先连接到名为example.db的SQLite3数据库,然后创建一个名为example_table的表,并向其中插入一些数据。然后,它查询、更新和删除表中的数据,最后关闭数据库连接。

参考

菜鸟教程-sqlite3

廖雪峰-sqlite3-python教程

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

早睡的叶子

你的鼓励就是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值