zoukankan      html  css  js  c++  java
  • Python学习笔记21:数据库操作(sqlite3)

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


    一 数据库设计

    我将创建一个简单的关系型数据库,为一个书店存储书的分类和价格。
    数据库中包括两个表:category用于记录分类,book用于记录某个书的信息。
    一本书归属于某一个分类,因此book有一个外键(foreign key),指向catogory表的主键id。

    【category】
    id int,sort int,name text
    
    
    【book】
    id int,sort int,name text,price real,category int


    二 创建数据库

    首先创建数据库,以及数据库中的表。
    在使用connect()链接数据库后,能够通过定位指针cursor,来运行SQL语句。

    import sqlite3
    
    
    # data.db is a db file in the working directory.
    conn = sqlite3.connect("data.db")
    
    
    c = conn.cursor()
    
    
    # create tables
    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()
    
    
    # close the connection with the database
    conn.close()

    SQLite的数据库是一个磁盘上的文件,如上面的data.db,因此整个数据库能够方便的移动或复制。
    data.db一開始不存在,所以SQLite将自己主动创建一个新文件。
    利用execute()命令,我运行了两个SQL命令,创建数据库中的两个表。创建完毕后,保存并断开数据库连接。


    三 插入数据

    上面创建了数据库和表,确立了数据库的抽象结构。以下将在同一数据库中插入数据:

    import sqlite3
    
    
    conn = sqlite3.connect("data.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()
    

    插入数据相同能够使用execute()来运行完整的SQL语句。
    SQL语句中的參数,使用"?"作为替代符号,并在后面的參数中给出详细值。
    这里不能用Python的格式化字符串,如"%s",由于这一使用方法easy受到SQL注入攻击。
    我也能够用executemany()的方法来运行多次插入,添加多个记录。
    每一个记录是表中的一个元素,如上面的books表中的元素。


    四 查询

    在运行查询语句后,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)


    五 更新和删除记录

    能够更新某个记录,或者删除记录:


    import sqlite3
    
    
    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')

    假设删除data.db,那么整个数据库会被删除。

  • 相关阅读:
    第十四周课程总结&实验报告(简单记事本的实现)
    第十三周课程总结
    第十二周
    第十一周课程总结
    第十周课程总结
    第九周课程总结&实验报告(七)
    第八周课程总结&实验报告(六)
    第七周课程总结&实验报告(五)
    第六周&java实验报告四
    全局变量
  • 原文地址:https://www.cnblogs.com/mfrbuaa/p/4217172.html
Copyright © 2011-2022 走看看