美文网首页
python3 使用sqlite3数据库

python3 使用sqlite3数据库

作者: 510bb14393e1 | 来源:发表于2022-09-29 10:32 被阅读0次

    sqlite3 数据库是 Python 自带的数据库,不需要额外安装模块,而且操作简单。
    1.创建数据库,我们直接在桌面右键单击选择《新建》,选择《文本文档》,然后把这个文件重名为a.db在复制到d盘根目录(放其他盘也可以,但路径中不能有中文), 这样我们的数据库就创建好了,如下图


    QQ图片20220929093826.png

    2.连接数据库

    #连接数据库
    db=sqlite3.connect("d:\\a.db")
    

    3.创建表数据

     #创建表
     db.execute("""CREATE TABLE user (id integer primary key AUTOINCREMENT,title text NULL,)""")
    

    id integer primary key AUTOINCREMENT
    这句sql语句代表id为主键并进行自增
    title text NULL
    这句sql语句代表创建text字段,数据可以是空的
    4.查询数据

    #查询数据
    def getAll(path):
        db=sqlite3.connect(path)
        cu=db.cursor()
        cu.execute("SELECT * FROM user")
        res=cu.fetchall()
        cu.close()
        db.close()
        return res
    

    5.添加数据

    #添加
    def add(title,path):
        db=sqlite3.connect(path)
        cu=db.cursor()
        cu.execute("insert into user values(NULL,'"+title+"')")
        db.commit()
        cu.close()
    

    6.删除数据

    #删除
    def delate(name,path):
        db=sqlite3.connect(path)
        cu=db.cursor()
        cu.execute("delete from user where id="+str(name))
        db.commit()
        cu.close()
    

    7.分页查询

    #分页
    def limit(p,path):
        db=sqlite3.connect(path)
        cu=db.cursor()
        cu.execute("SELECT * FROM user limit "+p+",10")
        res=cu.fetchall()
        cu.close()
        db.close()
        return res
    

    一些简单常用的sql语句

    #模糊查询
    select * from user where title like '%小明%'
    #统计数据总数
    select count(id) from user
    #根据id查询
    select * from user where id = 1
    #根据id删除记录
    delete from user where id = 1
    #插入数据
    insert into user values(NULL,‘小明’)
    #查询表所有数据
    select * from user
    #获取指定位置后面的10条数据 (分页)
    select * from user limit 1,10
    

    相关文章

      网友评论

          本文标题:python3 使用sqlite3数据库

          本文链接:https://www.haomeiwen.com/subject/xkohartx.html