Python标准库之sqlite3使用及实例

这篇文章主要介绍了Python标准库之sqlite3使用实例,本文讲解了创建数据库、插入数据、查询数据、更新与删除数据操作实例

Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配Python建网站,或者制作有数据存储需求的工具。SQLite还在其它领域有广泛的应用,比如HTML5和移动端。Python标准库中的sqlite3提供该数据库的接口。

创建一个简单的关系型数据库,为一个书店存储书的分类和价格。数据库中包含两个表:

category用于记录分类,

book用于记录某个书的信息。一本书归属于某一个分类,因此book有一个外键(foreign key),指向catogory表的主键id。

《Python标准库之sqlite3使用及实例》

1.创建数据库

SQLlte数据类型

SQLite能保存什么样的数据类型 ??   可以保存空值、整数、浮点数、字符串和blob。

什么是blob ?? 是二进制大对象。例如图片、音乐、zip文件。

什么是游标 ??   游标是在数据库中用来移动和执行查询的对象。

SQL的全部知识呢??? 远不止这些网站 http://www.runoob.com/sql/sql-tutorial.html 有一个很好的初学教程

《Python标准库之sqlite3使用及实例》

首先来创建数据库,以及数据库中的表。在使用connect()连接数据库后,我就可以通过定位指针cursor,来执行SQL命令,

SQLite的数据库是一个磁盘上的文件,如上面的test.db,因此整个数据库可以方便的移动或复制。test.db一开始不存在,所以SQLite将自动创建一个新文件。

利用execute()命令,我执行了两个SQL命令,创建数据库中的两个表。创建完成后,保存并断开数据库连接:

# -*- coding: utf-8 -*-
#创建一个访问数据库test.db的连接
import sqlite3
 
if __name__ == "__main__":

    # SQLiteCase01.db is a file in the working directory.
    conn = sqlite3.connect("SQLiteCase01.db") # 在此文件所在的文件夹打开或创建数据库文件
    c = conn.cursor() # 设置游标
    # create tables 创建一个含有id,name,password字段的表category和book
    c.execute('''CREATE TABLE category
          (id int primary key, 
          sort int, 
          name text)''')
    c.execute('''CREATE TABLE book
          (id int primary key, 
           sort int, 
           name text, 
           price real, 
           category int,
           FOREIGN KEY (category) REFERENCES category(id))''')
    # save the changes
    conn.commit()  # python连接数据库默认开启事务,所以需先提交
    # close the connection with the database
    conn.close()   # 关闭连接

2.添加数据

要添加一些数据到表中,需要使用insert命令和一些特殊的格式

上面创建了数据库和表,确立了数据库的抽象结构。

插入数据同样可以使用execute()来执行完整的SQL语句。SQL语句中的参数,使用”?”作为替代符号,并在后面的参数中给出具体值。这里不能用Python的格式化字符串,如”%s”,因为这一用法容易受到SQL注入攻击。也可以用executemany()的方法来执行多次插入,增加多个记录。每个记录是表中的一个元素,如上面的books表中的元素。

下面将在同一数据库中插入数据:

import sqlite3
conn = sqlite3.connect("test.db")
c    = conn.cursor()
books = [(1, 1, 'Cook Recipe', 3.12, 1),
            (2, 3, 'Python Intro', 17.5, 2),
            (3, 2, 'OS Intro', 13.6, 2),
           ]
# execute "INSERT" 
c.execute("INSERT INTO category VALUES (1, 1, 'kitchen')")
# using the placeholder
c.execute("INSERT INTO category VALUES (?, ?, ?)", [(2, 2, 'computer')])
# execute multiple commands
c.executemany('INSERT INTO book VALUES (?, ?, ?, ?, ?)', books)
conn.commit()
conn.close()

其他案例代码:

import sqlite3


conn = sqlite3.connect('mytest.db')
cursor = conn.cursor()

print('hello SQL')

while True:
    name  = input('student\'s name')
    username = input('student\'s username')
    id_num = input('student\'s id number:')
 # '''insert语句 把一个新的行插入到表中'''

    sql = ''' insert into students
              (name, username, id)
              values
              (:st_name, :st_username, :id_num)'''
    # 把数据保存到name username和 id_num中
    cursor.execute(sql,{'st_name':name, 'st_username':username, 'id_num':id_num})
    conn.commit()
    cont = ('Another student? ')
    if cont[0].lower() == 'n':
        break
cursor.close()

《Python标准库之sqlite3使用及实例》

3.查询数据

执行查询语句后,Python将返回一个循环器,包含有查询获得的多个记录。你循环读取,也可以使用sqlite3提供的fetchone()和fetchall()方法读取记录:

import sqlite3
conn = sqlite3.connect('test.db')
c = conn.cursor()
# retrieve one record
c.execute('SELECT name FROM category ORDER BY sort')
print(c.fetchone())
print(c.fetchone())
# retrieve all records as a list
c.execute('SELECT * FROM book WHERE book.category=1')
print(c.fetchall())
# iterate through the records
for row in c.execute('SELECT name, price FROM book ORDER BY sort'):
    print(row)

其他案例:

《Python标准库之sqlite3使用及实例》

 

import sqlite3
import os
os.chdir('d:\\pycharm\\lesson\\sn01')

# conn = sqlite3.connect('D:\\pycharm\\lesson\\sn01\\SQL\\mytest.db')
conn = sqlite3.connect(r'./SQL/mytest.db')
cursor = conn.cursor()

# 查询所有的学生表
# sql = '''select * from students'''

''' 得到数据库中的名字'''
sql = "select rowid,  username from students"

# 执行语句
results = cursor.execute(sql)

# 遍历打印输出
all_students = results.fetchall()
for student in all_students:
    print(student)

《Python标准库之sqlite3使用及实例》

4.更新与删除

你可以更新某个记录,或者删除记录:

conn = sqlite3.connect("test.db")
c = conn.cursor()
c.execute('UPDATE book SET price=? WHERE id=?',(1000, 1))
c.execute('DELETE FROM book WHERE id=2')
conn.commit()
conn.close()

你也可以直接删除整张表:

c.execute('DROP TABLE book')

5.SQLite Studio来查看SQLite数据文件

执行完成之后,可以发现在当前目录下会生成一个test.db的数据库文件。可以通过SQLite Studio来查看SQLite数据文件,该软件不需要安装,解压之后就可以使用

《Python标准库之sqlite3使用及实例》

官网下载地址:https://sqlitestudio.pl/index.rvt

6、读取数据库表中的数据

# 创建一个访问数据库test.db的连接
    conn = sqlite3.connect("test.db")
    # 创建游标
    c = conn.cursor()
    # 获取user表中所有的记录
    c.execute("SELECT * FROM user")
    #获取结果
    result = c.fetchall()
    #关闭连接
    conn.close()
    #查看数据
    print(result)
    #[(1, 'python', 1, 3, '2018-04-18 13:49:16')]

 

    原文作者:Goldxwang
    原文地址: https://blog.csdn.net/goldxwang/article/details/84726730
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞