2017年3月7日19:55:56

直接开始了解SQLite。

2017年3月19日10:08:19

中断了许多天,继续看。

About SQLite这篇文章当中简单介绍了SQLite,读完它之后我再翻看了Support页面,觉得SQLite项目团队实在太特别:

  • 非常优异的产品(为众多世界知名企业google, facebook, APP, Microsoft等所使用)。
  • 免费且开源。
  • 很小的维护团队(international team中只有3个人。)
  • 同时提供免费与付费支持。

在介绍当中提到SQLite是一个嵌入型SQL数据库,它直接读写磁盘文件来进行数据的存储,并且有着极佳的可移植性。

sqlite3 — DB-API 2.0 interface for SQLite databases中,sqlite3是在python中用来操作SQLite数据库的模块,其中提供了多种多个操作数据库的函数。当当前自己使用的是python2.x,能够使用这个吗?这个问题先不管,接着阅读下一篇文章 Build a CRUD Web App With Python and Flask,这篇文章里面介绍了通过python和falsk来创建一个职工管理web应用,功能比这周任务强,看懂了这篇教程本周任务相信也可以搞定。这篇教程里面使用了python2.7,看来刚刚提到的问题也可以迎刃而解了。然而,在阅读上面提到的这篇教程时发现它使用的数据库不是SQLite而是MySQL,便决定继续走下一步,暂停阅读。最后一篇参考文章Sams Teach Yourself SQL in 10 Minutes是介绍SQL,与SQLite的操作无关,在进行下一个子任务“存储数据”之前,先搜索下“Python2.x中使用SQLite的问题”。

在阅读了SQLite Python tutorial之后发现上面自己所担心的phthon版本问题并不存在,因为sqlite3当中的“3”是标记SQLite的版本,并不意味着一定要匹配python3.x才能使用。

To work with this tutorial, we must have Python language, SQLite database, pysqlite language binding and the sqlite3 command line tool installed on the system. If we have Python 2.5+ then we only need to install the sqlite3 command line tool.

同时发现了这篇文章包含了数据库的操作过程,其中的创建与更新操作正是当前所需要的。

1.使用with语句的INSERT操作。

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

con = lite.connect('test.db')

with con:

    cur = con.cursor()    
    cur.execute("CREATE TABLE Cars(Id INT, Name TEXT, Price INT)")
    cur.execute("INSERT INTO Cars VALUES(1,'Audi',52642)")
    cur.execute("INSERT INTO Cars VALUES(2,'Mercedes',57127)")
    cur.execute("INSERT INTO Cars VALUES(3,'Skoda',9000)")
    cur.execute("INSERT INTO Cars VALUES(4,'Volvo',29000)")
    cur.execute("INSERT INTO Cars VALUES(5,'Bentley',350000)")
    cur.execute("INSERT INTO Cars VALUES(6,'Citroen',21000)")
    cur.execute("INSERT INTO Cars VALUES(7,'Hummer',41400)")
    cur.execute("INSERT INTO Cars VALUES(8,'Volkswagen',21600)")

2.Parameterized queries时的UPDATE操作。

这里有个疑问:前面提到使用with语句的时候可以不用再执行commit,为什么这里UPDATE的时候会使用这个操作呢?

#!/usr/bin/python
# -*- coding: utf-8 -*-

import sqlite3 as lite
import sys

uId = 1
uPrice = 62300

con = lite.connect('test.db')

with con:

    cur = con.cursor()    

    cur.execute("UPDATE Cars SET Price=? WHERE Id=?", (uPrice, uId))        
    con.commit()

    print "Number of rows updated: %d" % cur.rowcount

  • scotch是一个web开发的自学网站,网站的外观看起来非常不错。
  • CRUD的指代针对数据库的几种常用操作——Create, Read, Update和Delete。

results matching ""

    No results matching ""