一 sqlite 与 python 的类型对应

二 实例


import sqlite3

def sqlite_basic():
    # Connect to db
    conn = sqlite3.connect('test.db')
    # create cursor
    c = conn.cursor()
    # Create table
    c.execute('''
              create table if not exists stocks
              (date text, trans text, symbol text,
              qty real, price real)
              '''
             )
    # Insert a row of data
    c.execute('''
              insert into stocks
              values ('2006-01-05','BUY','REHT',100,35.14)
              '''
             )
    # query the table
    rows  = c.execute("select * from stocks")
    # print the table
    for row in rows:
      print(row)
    # delete the row
    c.execute("delete from stocks where symbol=='REHT'")
    # Save (commit) the changes
    conn.commit()
    # Close the connection
    conn.close()
    
def sqlite_adv():
    conn = sqlite3.connect('test2.db')
    c = conn.cursor()
    c.execute('''
              create table if not exists employee
              (id text, name text, age inteage)
              ''')
    # insert many rows
    for t in [('1', 'itech', 10),
              ('2', 'jason', 10),
              ('3', 'jack', 30),
             ]:
        c.execute('insert into employee values (?,?,?)', t)
    # create index
    create_index = 'CREATE INDEX IF NOT EXISTS idx_id ON employee (id);'
    c.execute(create_index)
    # more secure
    t = ('jason',)
    c.execute('select * from employee where name=?', t)
    # fetch query result
    for row in c.fetchall():
      print(row)
    conn.commit()
    conn.close()
    
def sqlite_adv2():
    # memory db
    con = sqlite3.connect(":memory:")
    cur = con.cursor()
    # execute sql 
    cur.executescript('''
    create table book(
        title,
        author,
        published
    );
    insert into book(title, author, published)
    values (
        'AAA book',
        'Douglas Adams',
        1987
    );
    ''')
    rows = cur.execute("select * from book")
    for row in rows:
      print("title:" + row[0])
      print("author:" + row[1])
      print("published:" + str(row[2]))
      
def sqlite_adv3():
    import datetime     # Converting SQLite values to custom Python types
    # Default adapters and converters for datetime and timestamp
    con = sqlite3.connect(":memory:", detect_types=sqlite3.PARSE_DECLTYPES|sqlite3.PARSE_COLNAMES)
    cur = con.cursor()
    cur.execute("create table test(d date, ts timestamp)")     today = datetime.date.today()
    now = datetime.datetime.now()     cur.execute("insert into test(d, ts) values (?, ?)", (today, now))
    cur.execute("select d, ts from test")
    row = cur.fetchone()
    print today, "=>", row[0], type(row[0])
    print now, "=>", row[1], type(row[1])     cur.execute('select current_date as "d [date]", current_timestamp as "ts [timestamp]" from test')
    row = cur.fetchone()
    print "current_date", row[0], type(row[0])
    print "current_timestamp", row[1], type(row[1])       
#sqlite_basic()
#sqlite_adv()
#sqlite_adv2()
#sqlite_adv3()

完!

python类库26[sqlite]的更多相关文章

  1. python类库26[web2py之基本概念]

    一 web2py的应用的执行环境Models,Controllers和views所在的执行环境中,以下对象已经被默认地导入: Global Objects:  request,response,ses ...

  2. 二十六. Python基础(26)--类的内置特殊属性和方法

    二十六. Python基础(26)--类的内置特殊属性和方法 ● 知识框架 ● 类的内置方法/魔法方法案例1: 单例设计模式 # 类的魔法方法 # 案例1: 单例设计模式 class Teacher: ...

  3. Python中使用SQLite

    参考原文 廖雪峰Python教程 使用SQLite SQLite是一种嵌入式数据库,它的数据库就是一个文件.由于SQLite本身是用C写的,而且体积很小,所以经常被集成到各种应用程序中,甚至在IOS和 ...

  4. python类库32[多进程同步Lock+Semaphore+Event]

    python类库32[多进程同步Lock+Semaphore+Event]   同步的方法基本与多线程相同. 1) Lock 当多个进程需要访问共享资源的时候,Lock可以用来避免访问的冲突. imp ...

  5. PyCharm无法找到已安装的Python类库的解决方法

    一.问题描述 软件系统:Windows10.JetBrains PyCharm Edu 2018.1.1 x64 在命令行cmd中安装python类库包Numpy.Matplotlib.Pandas. ...

  6. python 数据库操作 SQLite、MySQL 摘录

    转自: http://www.cnblogs.com/windlaughing/p/3157531.html 不管使用什么后台数据库,代码所遵循的过程都是一样的:连接 -> 创建游标 -> ...

  7. 在Ubuntu上升级SQLite,并让Python使用新版SQLite

    (本文适用于Debian系的Linux,如Ubuntu.Raspbian等等.) 在Linux上,Python的sqlite3模块使用系统自带的SQLite引擎,然而系统自带的SQLite可能版本太老 ...

  8. SnowNLP:一个处理中文文本的 Python 类库[转]

    SnowNLP是一个python写的类库,可以方便的处理中文文本内容,是受到了TextBlob的启发而写的,由于现在大部分的自然语言处理库基本都是针对英文的,于是写了一个方便处理中文的类库,并且和Te ...

  9. SQLite in Python: 如何在Python中使用SQLite数据库

    SQLite3 可使用 sqlite3 模块与 Python 进行集成.sqlite3 模块是由 Gerhard Haring 编写的.它提供了一个与 PEP 249 描述的 DB-API 2.0 规 ...

随机推荐

  1. IDEA使用git提交代码时,点了commit之后卡死在performing code analysis部分,或者performing code analysis结束后没有进入下一步操作

    把"Perform code analysis" 和 "Check TODO" 复选框前面的勾去掉就好了. 这个可能是因为所分析的目标文件太大了,造成一直分析不 ...

  2. Python 解决八皇后问题

    问题介绍 八皇后问题是一个以国际象棋为背景的问题:如何能够在 \(8\times8\) 的国际象棋棋盘上放置八个皇后,使得任何一个皇后都无法直接吃掉其他的皇后?为了达到此目的,任两个皇后都不能处于同一 ...

  3. 安装SQL Server 2008反复提示需要安装MICROSOFT NET FRAMEWORK 3 5 SP1的一个

    在安装过.net  framework 4的系统中,安装sql server 2008的安装前提之一MICROSOFT .NET FRAMEWORK 3.5 SP1时,可能已经安装并重启了,还是提示安 ...

  4. Stream流实现斐波那契数列

    1.前言 我们都知道斐波那契数列有很多种实现方法,在jdk1.8以前没有流操作,只能通过递归或者迭代等其他方式来实现斐波那契数列, 但是jdk1.8以后,有了流操作,我们就可以使用流来实现斐波那契数列 ...

  5. 【计算机视觉】阶编码本模型(Multi phase codebook model)

    转自:http://www.cnblogs.com/xrwang/archive/2012/04/24/MPCBBGM.html 多阶编码本模型(Multi phase codebook model) ...

  6. 红帽学习记录[RHCE] ISCSI远程块储存

    目录 iSCSI 定义 组件术语 启动器 目标 ACL 发现 IQN 登录 LUN 节点 门户 TPG 搭建一个iSCSI服务 提供一个iSCSI目标 配置iSCSI客户端 iSCSI 定义 SCSI ...

  7. java期末考试

    水仙花数 package txt; public class shuixianhua { public static void main(String[] args) { // TODO Auto-g ...

  8. Flink初探-为什么选择Flink

    本文主要记录一些关于Flink与storm,spark的区别, 优势, 劣势, 以及为什么这么多公司都转向Flink. What Is Flink 一个通俗易懂的概念: Apache Flink 是近 ...

  9. Microsoft BarCode Control 16.0属性

    Labview(2018)可通过Active调用Microsoft BarCode Control 16.0来生成条形码, 参考资料如下: 生成效果: 二维码: 条形码: 执行程序发现修改线条宽度不影 ...

  10. C语言---程序的一般形式、数据类型、常量变量、运算符、表达式、格式化输入输出

    1. 程序的一般形式 (1)注释 ① 分类:单行注释( // ): 注释一行.多行注释( /**/ ): 在这个区间内,都属于多行注释,可以换行. ② 作用:提示代码的作用,提示思路   不写注释的后 ...