美文网首页
[py004] sqlite3上手急用

[py004] sqlite3上手急用

作者: Andy计算机专业 | 来源:发表于2020-06-06 10:43 被阅读0次

Friday, June 5, 2020 ---Andy

一、导入sqlite3模块+定义sql执行函数

import sqlite3

class MySqlite:
    def __init__(self,database="Andy.db"):
        self.database = database
        
    def execute(self,sql=''):
        """执行sql语句,@return: select操作:rows-->[()...]"""
        try:
            # 1.连接数据库
            conn = sqlite3.connect(self.database)
            # 2.执行sql:以查询数据库里面包含的所有表为例
            rows = [row for row in conn.execute(sql)]
            # 插入-删除-修改:需要提交
            conn.commit()
            # 3.关闭数据库
            conn.close()
            return rows
        except Exception as e:
            print(e)
            
    def tables(self):
        """查看所有表"""
        return self.execute(sql='select name from sqlite_master')
        
    def table_info(self,table='sqlite_master'):
        """查看表的结构"""
        return self.execute(sql=f"PRAGMA table_info({table})")
        
    def show(self,table='sqlite_master'):
        """查看表的数据"""
        return self.execute(sql=f"select * from {table}")

二、创建表,查询存在的表,查看表结构

# 2-1.自动创建sqlite3_test_db.db数据库文件,并创建表
sqli = MySqlite('sqlite3_test_db.db')
sqli.execute("create table user(name text PRIMARY KEY NOT NULL, age int)")
# 2-2.查询当前数据库有哪些表
sqli.tables()
[('user',), ('sqlite_autoindex_user_1',)]
# 2-3.查询表结构
sqli.table_info(user)
[(0, 'name', 'text', 1, None, 1), (1, 'age', 'int', 0, None, 0)]

三、数据增删改查

# 3-1 增
sqli.execute("insert into user values('Andy',18)")
sqli.execute("insert into user values('Amanda',18)")
# 3-2 删
sqli.execute("delete from user where name = 'Amanda'")
# 3-3 改
sqli.execute("update user set age=19 where name = 'Andy'")
# 3-4 查
sqli.execute("select * from user")
[('Andy', 19)]

【完】

[1].过程中有任何问题,欢迎交流!Q597966823

  让知识或技术实现其最大的价值,欢迎收藏自用、转载分享,转载请注明原文出处,谢谢!

相关文章

  • [py004] sqlite3上手急用

    Friday, June 5, 2020 ---Andy 一、导入sqlite3模块+定义sql执行函数 二、创...

  • sqlite3 简介

    初次接触sqlite3,她就给了我一种小巧,轻便,易上手的感觉。没有那么多的约束,也没有那么让人琢磨不透。 大致语...

  • 使用sqlite3存储奥斯卡金像奖提名信息

    SQLite3 可使用 sqlite3 模块与 Python 进行集成。sqlite3 模块是由 Gerhard ...

  • sqlite的用法

    SQLite3 可使用 sqlite3 模块与 Python 进行集成。sqlite3 模块是由 Gerhard ...

  • SQLite3深入浅出

    文章目录: sqlite3 基础语句 sqlite3 API sqlite3 线程安全 FMDB 基础语句: 创建...

  • sqlite3简单命令行

    sqlite3简单命令行1、输入" sqlite3 + 数据库名.db " (如: " sqlite3 Book...

  • Python数据分析基础----第二十二天

    数据库 Python内置的sqlite3模块 import sqlite3 创建sqlite3内存数据库 创建带有...

  • sqlite3

    来源sqlite3 进入sqlite3数据库命令行 .exit/.quit 退出sqlite3命令行 sqlite...

  • sqlite3 与 pandas

    对于一个 sqlite3 的小白,通过 sqlite3 的表头使用 pandas 来获取 sqlite3 的数据内...

  • sqlite操作简介

    进入sqlite3数据库命令: sqlite3 退出sqlite3命令行: .exit/.quit 创建一个新的数...

网友评论

      本文标题:[py004] sqlite3上手急用

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