zoukankan      html  css  js  c++  java
  • 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"
  • 相关阅读:
    爬取某人的微博信息
    Scrapy 爬取新浪微博
    《python3网络爬虫开发实战》--Scrapy
    《python3网络爬虫开发实战》--pyspider
    《python3网络爬虫开发实战》--APP爬取
    《python3网络爬虫开发实战》--模拟登陆
    《python3网络爬虫开发实战》--代理的使用
    用selenium爬取淘宝商品
    《python3网络爬虫开发实战》--动态渲染页面爬取
    Ajax爬取今日头条街拍美图
  • 原文地址:https://www.cnblogs.com/shihao/p/2324905.html
Copyright © 2011-2022 走看看