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"

1 thought on “Python SQLite的使用经验”

Leave a Reply

Your email address will not be published. Required fields are marked *