• Python SQLite的使用经验


    SQLite是 一款轻量级的数据库,很适合用着移动设备上,或者是客户端程序。SQLite的优点有:1. 不需要为数据库起一个单独的进程 2. 整个数据库可以随时拷贝走 3. 不需要任何配置。从Python 2.5开始,SQLite就在标准库了,所以用起来比较方便。下面是我使用过程中的一些使用经验。

    连接到数据库?很简单。

    import sqlite3 conn = sqlite3.connect('/tmp/sqlite_db') cur = conn.cursor()

    接下来干嘛呢?建一张表吧。这里需要注意的是,SQLite不支持在创建表的同时创建索引,所以要分两步走,先创建表然后再创建索引

    create_table_stmt = '''     CREATE TABLE IF NOT EXISTS test_table (     id TEXT,     duration INTEGER,     event_date TEXT,     parameter TEXT );''' create_index = 'CREATE INDEX IF NOT EXISTS idx_id ON test_table (id);' cur.execute(create_table_stmt) cur.execute(create_index) conn.commit()

    然后往里面插一点数据吧,SQLite只支持5种基本的数据类型


    NULL. The value is a NULL value.
    INTEGER. The value is a signed integer, stored in 1, 2, 3, 4, 6, or 8 bytes depending on the magnitude of the value.
    REAL. The value is a floating point value, stored as an 8-byte IEEE floating point number.
    TEXT. The value is a text string, stored using the database encoding (UTF-8, UTF-16BE or UTF-16LE).
    BLOB. The value is a blob of data, stored exactly as it was input.

    问题来了,SQLite的时间和日期类型在哪里?原来SQLite可以把时间日期保存在一下几种数据类型里面


    TEXT as ISO8601 strings (“YYYY-MM-DD HH:MM:SS.SSS”).
    REAL as Julian day numbers, the number of days since noon in Greenwich on November 24, 4714 B.C. according to the proleptic Gregorian calendar.
    INTEGER as Unix Time, the number of seconds since 1970-01-01 00:00:00 UTC.

    insert_stmt = 'insert into test_table values (?, ?, ?, ?)' record = ('test', 123, '2011-11-30 12:34:56', 'hello') cur.execute(insert_stmt, record) conn.commit()

    把日期保存为字符串以后,不能直接拿出来直接当日期用,在用之前要调用SQLite的date函数

    例如找前一天存进去的数据:

    SELECT      id,      duration,      event_date,      parameter  FROM test_table WHERE     DATE(event_date) = DATE('now', '-1 day', 'localtime') ORDER BY id, event_date

    SQLite没有show tables,怎么查询数据库里面有什么表?

    SELECT name FROM sqlite_master WHERE TYPE = "table"
  • 相关阅读:
    STM32 HAL库学习笔记
    嵌入式Linux学习笔记
    AVR_Interrupt
    shutdown命令用法
    ULINK2 USB电脑无法识别(连接电脑后,设备管理器显示未知设备)
    MDK中编译程序后Program Size详解
    Keil(MDK-ARM)系列教程(三)_工程目标选项配置(Ⅰ)
    第48章 MDK的编译过程及文件类型全解
    Do not access Object.prototype method ‘hasOwnProperty’ from target object no-prototype-builtins
    让vscode按照eslint进行格式化
  • 原文地址:https://www.cnblogs.com/shihao/p/2324905.html
Copyright © 2020-2023  润新知