一 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. 大众点评cat监控平台搭建

    参考官方文档:https://github.com/dianping/cat/wiki/readme_server 1.数据库相关 (1)创建数据库cat,并执行以下sql创建相关表: CREATE ...

  2. Java学习之==>JDBC

    一.概述 官方解释: JDBC(Java DataBase Connectivity,java数据库连接)是一种用于执行SQL语句的 Java API,可以为多种关系型数据库提供统一访问,它由一组用 ...

  3. docker扩容

    方法一. https://www.cnblogs.com/atuotuo/p/7217331.html 只需要修改 dockerd 的启动参数啊 增加 --data-root 把 /var/lib/d ...

  4. java之 Mybatis框架

    1.三层框架: 表现层: 是用于展示数据 业务层: 是处理业务需求 持久层: 是和数据库交互 注:MyBatis在持久层 2.JDBC操作数据库 public static void main(Str ...

  5. P3367 【模板】并查集

    喵呜~~(题面) 这题其实很早就过了,但是呢,以前过的时候真的基本上是CtrlC+CtrlV,这次把代码重新码了一遍,对并查集也有了一个基本清晰的认识 #include<iostream> ...

  6. python每日一练:0002题

    第 0002 题:将 0001 题生成的 200 个激活码(或者优惠券)保存到 MySQL 关系型数据库中. 示例代码: import os import string import random i ...

  7. 应用安全 - 中间件 - IIS - 漏洞 - 汇总

    简介 支持协议 HTTP HTTP/2 HTTPS FTP FTPS SMTP NNTP等 支持操作系统 NT/2000/XP Professional/Server 2003及后续版本(XP Hom ...

  8. Flask的 sqlalchemy 操作要点

    1.filter和filter_by的区别 filter,使用复杂的过滤条件,一般用两个等号进行匹配 filter,使用简单的过滤条件,一般用一个等号进行匹配 Answer.query.filter( ...

  9. BATJ的常见java面试题

    JAVA基础 JAVA中的几种基本数据类型是什么,各自占用多少字节. String类能被继承吗,为什么. 不可以,因为String类有final修饰符,而final修饰的类是不能被继承的,实现细节不允 ...

  10. 初步学习jquery学习笔记(六)

    jquery学习笔记六 AJAX 简介 AJAX 是与服务器交换数据的技术,它在不重载全部页面的情况下,实现了对部分网页的更新. load() 方法 load() 方法从服务器加载数据,并把返回的数据 ...