zoukankan      html  css  js  c++  java
  • PYTHON——数据存储:SQLite数据库

    SQLite简介:
      SQLite,是一款轻型的数据库,是遵守ACID的关系型数据库管理系统,它包含在一个相对小的C库中。它是D.RichardHipp建立的公有领域项目。它的设计目标是嵌入式的,而且目前已经在很多嵌入式产品中使用了它,它占用资源非常的低,在嵌入式设备中,可能只需要几百K的内存就够了。它能够支持Windows/Linux/Unix等等主流的操作系统,同时能够跟很多程序语言相结合,比如Tcl、C#、PHP、Java等,还有ODBC接口,同样比起Mysql、PostgreSQL这两款开源的世界著名数据库管理系统来讲,它的处理速度比他们都快。SQLite第一个Alpha版本诞生于2000年5月。 至2015年已经有15个年头,SQLite也迎来了一个版本 SQLite 3已经发布。
      可以通过官网下载SQLite:  http://www.sqlite.org
      SQLite数据库的管理工具很多,SQLite官方提供的是命令行的管理工具,不方便。建议采用DB Browser for SQLite,这是一款免费开源的SQLite数据库管理工具。官网下载地址:http://sqlitebrowser.org。

    用python操作SQLite数据库实例:

    import sqlite3
    import os

    dbPath = 'data.sqlite'
    # 只有data.sqlite文件不存在时才创建该文件。
    if not os.path.exists(dbPath):
       # 创建SQLite数据库
    conn = sqlite3.connect(dbPath)
      #获取sqlite3.Cursor对象
    c = conn.cursor()
      #创建persons数据库表
    c.execute('''CREATE TABLE persons
    (id INT PRIMARY KEY NOT NULL,
    name TEXT NOT NULL,
    age INT NOT NULL,
    address CHAR(50),
    salary REAL);''')
      #修改数据库后必须调用commit方法提交才能生效
    conn.commit()
      #关闭数据库
    conn.close()
    print('数据库创建成功.')

    conn=sqlite3.connect(dbPath)
    c = conn.cursor()
    #删除persons表中的所有数据
    c.execute('delete from persons')
    #往persons表插入以下4条记录
    c.execute("insert into persons(id,name,age,address,salary)
    values(1,'Bill', 32,'California',20000.12)")
    c.execute("insert into persons(id,name,age,address,salary)
    values(2,'Mary', 26,'Texas',1234)")
    c.execute("insert into persons(id,name,age,address,salary)
    values(3,'John', 36,'Norway',5432)")
    c.execute("insert into persons(id,name,age,address,salary)
    values(4,'Joe', 16,'Rich-Mond',6543)")
    #必须提交,修改才能生效
    conn.commit()
    print('数据插入成功')
    #查询语句,生成一个对象
    persons = c.execute('select id,name,age,address,salary from persons order by age')
    print(type(persons))
    result = []
    #将sqlite3.Cursor对象中的数据转换成列表
    for person in persons:
    values={}
    #生成键值对
    values['id'] = person[0]
    values['name'] = person[1]
    values['age'] = person[2]
    values['address'] = person[3]
    values['salary'] = person[4]
    print(values)
    result.append(values)
    conn.close()
    print(result)

    # 还可以继续生成json字符串
    import json
    # 将查询结果转换为字符串形式,如果要将数据通过网络传输,就需要首先转换为字符串形式才能传输。
    resultstr = json.dumps(result)
    print(resultstr)


    参考文献:
    1、《python从菜鸟到高手》,作者:李宁
  • 相关阅读:
    bash八大扩展一网打尽
    MySQL命令行导出数据库
    Windows 7上的DirectX 11.1
    把KlayGE嵌入其他GUI框架
    KlayGE的资源载入系统
    学习路漫漫……
    写下我的第一篇Post,呵呵
    今天学习:CSS中的类class和标识id选择符(.和#号)
    Remove Duplicates from Unsorted List
    2012 TODO List
  • 原文地址:https://www.cnblogs.com/chenhaiming/p/9882438.html
Copyright © 2011-2022 走看看