zoukankan      html  css  js  c++  java
  • SQLite数据库的使用说明

    一、数据库的使用笔记

     数据库的使用流程:

      关于Sqlite3的介绍说明:

      SQLite是一种嵌入式数据库,它的数据库就是一个文件。由于SQLite本身是C写的,而且体积很小,所以,经常被集成到各种应用程序中,iOS和Android的App中都可以集成。 Python就内置了SQLite3,所以,在Python中使用SQLite,不需要安装任何东西,直接使用。 在使用SQLite前,我们先要搞清楚几个概念: 表是数据库中存放关系数据的集合,一个数据库里面通常都包含多个表,比如学生的表,班级的表,学校的表,等等。表和表之间通过外键关联。 要操作关系数据库,首先需要连接到数据库,一个数据库连接称为Connection; 连接到数据库后,需要打开游标,称之为Cursor,通过Cursor执行SQL语句,然后,获得执行结果。 Python定义了一套操作数据库的API接口,任何数据库要连接到Python,只需要提供符合Python标准的数据库驱动即可。

     

      常用命令有:

    sqlite3.connect() 打开一个到 SQLite 数据库文件 database 的链接。
    connection.cursor() 创建一个 cursor
    cursor.execute() sqlite3模块支持两种类型的占位符:问号和命名占位符(命名样式)
    connection.commit() 提交当前的事务。
    connection.close()

    关闭数据库连接。

      

      然后是建立一个简单的数据库

        代码如下

        

     1 def SQLite_Test():
     2     # =========== 连接数据库 ============
     3     # 1. 连接本地数据库
     4     connectA = sqlite3.connect("example.db")
     5     # 2. 连接内存数据库,在内存中创建临时数据库
     6     connectB = sqlite3.connect(":memory:")
     7 
     8     # =========== 创建游标对象 ============
     9     cursorA = connectA.cursor()
    10     cursorB = connectB.cursor()
    11 
    12     # =========== 创建表 ============
    13     cursorA.execute("CREATE TABLE class(id real, name text, age real, sex text)")
    14     cursorB.execute("CREATE TABLE family(relation text, job text, age real)")
    15 
    16     # =========== 插入数据 ============
    17     cursorA.execute("INSERT INTO class VALUES(1,'Jock',8,'M')")
    18     cursorA.execute("INSERT INTO class VALUES(2,'Mike',10,'M')")
    19     # 使用 ? 占位符
    20     cursorA.execute("INSERT INTO class VALUES(?,?,?,?)", (3,'Sarah',9,'F'))
    21 
    22     families = [
    23         ['Dad', 'CEO', 35],
    24         ['Mom', 'singer', 33],
    25         ['Brother', 'student', 8]
    26     ]
    27     cursorB.executemany("INSERT INTO family VALUES(?,?,?)",families)
    28 
    29     # =========== 查找数据 ============
    30     # 使用 命名变量 占位符
    31     cursorA.execute("SELECT * FROM class WHERE sex=:SEX", {"SEX":'M'})
    32     print("TABLE class: >>>select Male
    ", cursorA.fetchone())
    33     cursorA.close()
    34     
    35     cursorB.execute("SELECT * FROM family ORDER BY relation")
    36     print("TABLE family:
    ", cursorB.fetchall())
    37     cursorB.close()
    38 
    39     # =========== 断开连接 ============
    40     connectA.close()
    41     connectB.close()
    42 import sqlite3
    43 SQLite_Test()

      效果如图:

    爬取信息并存为csv文件

     
  • 相关阅读:
    D3DPT_TRIANGLESTRIP 与 D3DPT_TRIANGLEFAN 的区别
    [转]DrawPrimitive 详解Direct3DDevice8
    sublime useful packages
    spring+freemarker 乱码解决办法
    vim 更改注释颜色
    git rollback
    从源码导入到github
    Laravel 安装
    Install Apache 2.2.15, MySQL 5.5.34 & PHP 5.5.4 on RHEL/CentOS 6.4/5.9 & Fedora 19-12 [转]
    Linux / Unix Command: rz
  • 原文地址:https://www.cnblogs.com/loverboy88/p/10947337.html
Copyright © 2011-2022 走看看