zoukankan      html  css  js  c++  java
  • sqlite 创建、插入、查询

    sqlite 简单实现

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Date    : 2020/4/14 11:54
    # @File    : sqlite.py
    # @Author  : BenLam
    # @Link    : https://www.cnblogs.com/BenLam/
    # @Version : PyCharm
    
    
    import sqlite3, time
    db_pwd="C:\data"
    connect = sqlite3.connect(db_pwd)
    cursor = connect.cursor()
    try:
    	sql = '''
    	create table test(
    		[id]        integer PRIMARY KEY autoincrement,
    		[uname]     varchar(100),
    		[title]     NONE,
    		[timestamp] DATETIME(50),
    		[url]     NONE
    		);
    	'''
    	cursor.execute(sql)
    except Exception as e:
    	if e == "table test already exists":
    		pass
    
    text = [1,2,3]
    text.append(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
    sql = '''insert into test (uname, title, timestamp, url) VALUES (?,?,?,?)'''
    cursor.execute(sql,text)
    connect.commit()
    
    sql = '''select * from test'''
    for _ in cursor.execute(sql):
    	print(_)
    connect.close()
    

    打印结果

    <sqlite3.Cursor object at 0x00000000022D1E30>
    (1, '1', 2, 3, '2020-04-14 17:49:38')
    

    类方法实现 sqlite

    #!/usr/bin/env python
    # -*- coding: utf-8 -*-
    # @Date    : 2020/4/15 11:54
    # @File    : sqlite.py
    # @Author  : BenLam
    # @Link    : https://www.cnblogs.com/BenLam/
    # @Version : PyCharm
    
    
    import sqlite3, time
    
    class sqlite(object):
        """
        sqlite3 缓存
        """
        def __init__(self):
            print(" 首次连数据库 ".center(59, "-"))
            self.connect(data_path="C:\data")
    
        def __del__(self):
            self.cursor.close()
            self.connect.close()
            print(" 关闭数据库 ".center(59, "-"))
    
        def connect(self, data_path):
            self.connect = sqlite3.connect(data_path)
            self.cursor = self.connect.cursor()
    
        def create(self, table):
            try:
                sql = '''
                create table {}(
                    [id]        integer PRIMARY KEY autoincrement,
                    [uname]     varchar(100),
                    [title]     NONE,
                    [timestamp] DATETIME(50),
                    [url]     NONE
                    );
                '''.format(table)
                self.cursor.execute(sql)
            except Exception as e:
                if "already exists" in str(e):
                    return True
                else:
                    print(f"创建数据表出错 - {e}")
                    return False
            self.connect.commit()
    
        def insert(self, sql, data):
            # 多条数据插入
            # self.cursor.executemany(sql, data)
            self.cursor.execute(sql, data)
            self.connect.commit()
    
        def select(self, sql):
            for _ in self.cursor.execute(sql):
                print(_)
    
    
    test = sqlite()
    table = "bili"
    select_sql = f'''select * from {table} where id = "1"'''
    insert_sql = f'''insert into {table} (uname, title, timestamp, url) VALUES (?,?,?,?)'''
    lis = [1, 1, time.strftime("%Y-%m-%d %H%M%S",time.localtime()), "https://www.cnblogs.com"]
    test.create(table)
    test.select(select_sql)
    test.insert(insert_sql, lis)
    

    打印结果

    -------------------------- 首次连数据库 -------------------------
    (1, '名字', '标题', '2020-04-14 16:53:31', 'https://www.cnblogs.com')
    -------------------------- 关闭数据库 --------------------------
    [Finished in 0.7s]
    
  • 相关阅读:
    CRC校验码原理、实例、手动计算
    RAID级别
    ffmbc——广播电视以及专业用途量身定制的FFmpeg
    Linux查看物理CPU个数、核数、逻辑CPU个数
    Linux服务器高并发实践经历
    Linux解压命令大全
    针对文件系统和网络性能的测试
    代码覆盖工具(gcov、lcov)的使用
    MYSQL的卸载
    Moosefs源代码分析
  • 原文地址:https://www.cnblogs.com/BenLam/p/12699702.html
Copyright © 2011-2022 走看看