一 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. Python学习笔记:(十二)输入输出

    一.格式化输出 1.str.format()函数,格式化输出值 2.将输出值转变为字符串,可以使用repr()和str() str()函数将返回一个易读的表达式形式: repr()返回一个解释器易读的 ...

  2. overflow-x scroll 内部元素滚动,父级容器代码

    display: -webkit-box; overflow-x: scroll; -webkit-overflow-scrolling: touch;

  3. 主机加固之windows2003

    这篇与上一篇的win7主机加固内容大体类似,部分有些不同.这篇也可以用来尝试加固windows XP. 1. 配置管理 1.1用户策略 注意:在对Windows系统加固之前先新建一个临时的系统管理员账 ...

  4. 剑指OFFER数据结构与算法分类

    目录 数据结构 算法 数据结构 数组 有序二维数组查找 数组相对位置排序 数组顺时针输出 把数组排成最小的数 数组中的逆序对 扑克牌顺子 数组中重复的数字 构建乘积数组 链表 链表反向插入ArrayL ...

  5. win10电脑休眠后无法唤醒的解决办法

    电脑的休眠功能,为长时间不用的电脑进行了关闭显示.硬盘停转的深度节能模式,不仅节约能源,还保护设备. 但有些时候也会出现一些问题,如休眠后无法唤醒,无法移动鼠标,敲击键盘都无效,最后只能长按电源键来强 ...

  6. 【VS开发】【智能语音处理】MATLAB 与 音频处理 相关内容摘记

    MATLAB 与 音频处理 相关内容摘记 MATLAB 与 音频处理 相关内容摘记 1 MATLAB 音频相关函数 1 MATLAB 处理音频信号的流程 2 音量标准化 2 声道分离合并与组合 3 数 ...

  7. C++ string 详细用法

    string不是STL的容器(知道这一点的时候我也很吃惊),但是它与STL容器有着很多相似的操作,不需要担心长度问题,还封装了多种多样的方法,十分好用. 用到的库 #include <strin ...

  8. D - 卿学姐与魔法

    卿学姐与魔法 Time Limit: 1200/800MS (Java/Others)     Memory Limit: 65535/65535KB (Java/Others) Submit Sta ...

  9. Javaweb实训-宠物医院-社区宠物医院的页面样式

    /* CSS Document */      /*        对于CSS来说  每一个元素默认的margin和padding就是0px.但是不同的浏览器会有一个默认的浏览器样式修改默认的marg ...

  10. 严重报错: Error configuring application listener of class org.springframework.web.context.ContextLoaderLis

    其实可能是你的jar文件没有同步发布到自己项目的lib目录中(如果你是用Maven进行构建的话) 可以试试 下面的办法 项目点击右键 点击 Properties 选择Deployment Assemb ...