惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

U
Unit 42
C
Cybersecurity and Infrastructure Security Agency CISA
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Know Your Adversary
Know Your Adversary
S
Securelist
I
Intezer
AWS News Blog
AWS News Blog
L
LINUX DO - 热门话题
P
Privacy International News Feed
Recent Announcements
Recent Announcements
cs.CL updates on arXiv.org
cs.CL updates on arXiv.org
博客园 - 聂微东
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Attack and Defense Labs
Attack and Defense Labs
N
News and Events Feed by Topic
The GitHub Blog
The GitHub Blog
C
Cyber Attacks, Cyber Crime and Cyber Security
Schneier on Security
Schneier on Security
N
Netflix TechBlog - Medium
爱范儿
爱范儿
B
Blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
C
CERT Recently Published Vulnerability Notes
Hacker News: Ask HN
Hacker News: Ask HN
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
Blog — PlanetScale
Blog — PlanetScale
WordPress大学
WordPress大学
S
Secure Thoughts
K
Kaspersky official blog
N
News | PayPal Newsroom
O
OpenAI News
Last Week in AI
Last Week in AI
C
Check Point Blog
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Cyberwarzone
Cyberwarzone
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tor Project blog
大猫的无限游戏
大猫的无限游戏
Vercel News
Vercel News
D
Docker
Hugging Face - Blog
Hugging Face - Blog
T
Threat Research - Cisco Blogs
Cisco Talos Blog
Cisco Talos Blog
The Register - Security
The Register - Security
博客园 - 司徒正美
Martin Fowler
Martin Fowler
人人都是产品经理
人人都是产品经理
P
Palo Alto Networks Blog

博客园 - 轻舟软件

轻舟分公司协作平台:统一管理、高效协作 [ERR] 1118 - Row size too large (> 8126) IDEA中Java代码修改后及时生效的方法 AI课堂笔记:AI编程 轻舟项目管理系统:台账・文件・协作・管控,让项目告别混乱,有序可控! 分公司项目的柔性管理(造价咨询、招标代理) 咨询行业——项目费用管控 咨询行业——项目管理模型 Java8:函数式接口、Lambda、Stream Java知识图谱(转) 简约至上 软件需求分析方法论(转) EasyUI的属性、事件、方法的使用 两位小数偶感 什么是函数? HQL分页查询、分组查询 MySql 、Oracle 获取表结构和字段信息 马云卸任演讲全文(2019-09-10) MySQL权限管理常用命令
python SQLite 访问组件
轻舟软件 · 2024-08-06 · via 博客园 - 轻舟软件
import os
import sqlite3
from sqlite3 import Error
from queue import Queue, Empty
from typing import List,Tuple, Any


class SQLiteDB:

    default_db_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    default_db_file = default_db_path+"/db/mydb.db"

    def __init__(self, db_file=None, max_connections=10):
        self.db_file = db_file or self.default_db_file
        self.max_connections = max_connections  # 连接池最大连接数
        self.pool = Queue(maxsize=max_connections)  # 连接池

        for _ in range(max_connections):
            self.pool.put(sqlite3.connect(db_file))

    # 获得数据库连接
    def _get_connection(self):
        try:
            return self.pool.get(timeout=5)
        except Empty:
            raise Exception("No available database connections")

    # 释放数据库连接
    def _release_connection(self, conn):
        self.pool.put(conn)

    # 执行SQL语句
    def _execute_sql(self, sql: str, params: Tuple[Any, ...] = ()):
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, params)
            conn.commit()
        finally:
            cursor.close()
            self._release_connection(conn)

    # 创建表格
    def create_table(self, create_table_sql):
        self._execute_sql(create_table_sql)

    # 删除表格
    def drop_table(self, table_name):
        sql = f'DROP TABLE IF EXISTS {table_name}'
        self._execute_sql(sql)

    # 插入数据
    def insert(self, table, data):
        columns = ', '.join(data.keys())
        placeholders = ', '.join('?' * len(data))
        sql = f'INSERT INTO {table} ({columns}) VALUES ({placeholders})'
        self._execute_sql(sql, tuple(data.values()))

    # 更新数据
    def update(self, table, data,  condition="1=1"):
        placeholders = ', '.join([f"{column} = ?" for column in data.keys()])
        sql = f'UPDATE {table} SET {placeholders} WHERE {condition}'
        self._execute_sql(sql, tuple(data.values()))

    # 删除数据
    def delete(self, table, condition="1=1"):
        sql = f'DELETE FROM {table} WHERE {condition}'
        self._execute_sql(sql)

    # 查询多条数据
    def find_all(self, table, condition="1=1"):
        sql = f'SELECT * FROM  {table} WHERE {condition}'
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql)
            return cursor.fetchall()
        finally:
            cursor.close()
            self._release_connection(conn)

    # 分页查询
    def find_page(self, table, page=1, page_size=10, condition="1=1"):
        offset = (page - 1) * page_size
        sql = f'SELECT * FROM  {table} WHERE {condition} LIMIT {page_size} OFFSET {offset}'
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql)
            return cursor.fetchall()
        finally:
            cursor.close()
            self._release_connection(conn)

    # 查询单条数据
    def find_one(self, table, condition="1=1"):
        sql = f'SELECT * FROM  {table} WHERE {condition}'
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql)
            return cursor.fetchone()
        finally:
            cursor.close()
            self._release_connection(conn)

    # 查询多条数据(自定义sql)
    def query_all(self, sql: str, params: Tuple[Any, ...] = ()) -> List[Tuple]:
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, params)
            return cursor.fetchall()
        finally:
            cursor.close()
            self._release_connection(conn)

    # 查询单条数据(自定义sql)
    def query_one(self, sql: str, params: Tuple[Any, ...] = ()) -> Tuple:
        conn = self._get_connection()
        cursor = conn.cursor()
        try:
            cursor.execute(sql, params)
            return cursor.fetchone()
        finally:
            cursor.close()
            self._release_connection(conn)


# 数据库定义,供各个应用程序使用
mydb = SQLiteDB('mydb.db')


# 使用示例
if __name__ == '__main__':

    db = SQLiteDB('example.db')

    # 创建表格
    create_table_sql = """ CREATE TABLE IF NOT EXISTS users (
                                            id integer PRIMARY KEY AUTOINCREMENT,
                                            name text NOT NULL,
                                            age integer,
                                            salary REAL,
                                            is_active BOOLEAN
                                        ); """
    db.create_table(create_table_sql)

    # 插入数据
    db.insert('users', {'name': 'Alice', 'age': 30, 'salary': 5000.88, 'is_active': False})
    db.insert('users', {'name': 'Tom', 'age': 40, 'salary': 6000.66, 'is_active': True})
    db.insert('users', {'name': 'Lily', 'age': 28, 'salary': 7000.77, 'is_active': True})
    db.insert('users', {'name': 'Bate', 'age': 25, 'salary': 9000.99, 'is_active': True})
    db.insert('users', {'name': 'Lucy', 'age': 28, 'salary': 3000.33, 'is_active': True})

    # 更新数据
    condition = "name='{}'".format("Alice") # 查询条件 name='Alice'
    db.update('users', {'age': 33, 'salary': 8000.88}, condition)

    # 查询数据
    condition = "name='{}'".format("Tom") # 查询条件 name='Tom'
    print(db.find_one("users", condition))
    print(db.find_all("users"))
    print(db.find_page("users",2,3))

    # 删除数据
    condition = "name='{}'".format("Alice") # 查询条件 name='Alice'
    db.delete('users', condition)
    # db_tools.delete('users')  # 删除所有数据

    print("删除数据后——————————————————")
    print(db.find_one("users"))
    print(db.find_all("users"))

    print("自定义Sql 查询——————————————————")

    sql = "SELECT * FROM users where name=? "
    print(db.query_one(sql, ("Tom",)))

    sql = "SELECT * FROM users where salary > ? and is_active = ?"
    print(db.query_all(sql, (7000, True)))

    # 删除表格
    db.drop_table('users')