X Tutup
>然而,敬虔加上知足的心便是大利了,因为我们没有带什么到世上来,也不能带什么去,只要有衣有食,就当知足。但那些想要发财的人,就陷在迷惑、落在网罗和许多无知有害的私欲里,叫人沉在败坏和灭亡中。贪财是万恶之根。有人贪恋钱财,就被引诱离了真道,用许多愁苦把自己刺透了。(1 TIMOTHY 6:6-10) #SQLite数据库 SQLite是一个小型的关系型数据库,它最大的特点在于不需要服务器、零配置。前面的两个数据库,不管是MySQL还是MongoDB,都需要“安装”,安装之后,运行起来,其实是已经有一个相应的服务器在跑着呢。 而SQLite不需要这样。首先Python已经将相应的驱动模块作为标准库一部分了,只要安装了Python,就可以使用;另外,它也不需要服务器,可以类似操作文件那样来操作SQLite数据库文件。还有一点也不错,SQLite源代码不受版权限制。 SQLite也是一个关系型数据库,所以SQL语句可以在里面使用。 跟操作MySQL数据库类似,对于SQLite数据库,也要通过以下几步: - 建立连接对象 - 连接对象方法:建立游标对象 - 游标对象方法:执行sql语句 ##建立连接对象 由于SQLite数据库的驱动已经在Python里面了,所以,只要引用就可以直接使用。并且在学过MySQL的基础上,理解本节能容就容易多了。 >>> import sqlite3 >>> conn = sqlite3.connect("23301.db") 这样就得到了连接对象,是不是比MySQL连接要简化了很多呢。在`sqlite3.connect("23301.db")`中,如果已经有了那个数据库,就连接上它;如果没有,就新建一个。注意,这里的路径可以随意指定的。 不妨到目录中看一看,是否存在了刚才建立的数据库文件。 /2code$ ls 23301.db 23301.db 果然有了一个文件。连接对象建立起来之后,就要使用连接对象的方法继续工作了。 >>> dir(conn) ['DataError', 'DatabaseError', 'Error', 'IntegrityError', 'InterfaceError', 'InternalError', 'NotSupportedError', 'OperationalError', 'ProgrammingError', 'Warning', '__call__', '__class__', '__delattr__', '__doc__', '__enter__', '__exit__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'close', 'commit', 'create_aggregate', 'create_collation', 'create_function', 'cursor', 'enable_load_extension', 'execute', 'executemany', 'executescript', 'interrupt', 'isolation_level', 'iterdump', 'load_extension', 'rollback', 'row_factory', 'set_authorizer', 'set_progress_handler', 'text_factory', 'total_changes'] ##游标对象 这一步跟MySQL也类似,要建立游标对象。 >>> cur = conn.cursor() 接下来对数据库内容的操作,都是用游标对象方法来实现: >>> dir(cur) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__iter__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'arraysize', 'close', 'connection', 'description', 'execute', 'executemany', 'executescript', 'fetchall', 'fetchmany', 'fetchone', 'lastrowid', 'next', 'row_factory', 'rowcount', 'setinputsizes', 'setoutputsize'] 看到熟悉的名称了:`close(), execute(), executemany(), fetchall()` ###创建数据库表 面对SQLite数据库,读者曾经数据的sql指令都可以照样使用。 >>> create_table = "create table books (title text, author text, lang text) " >>> cur.execute(create_table) 这样就在数据库23301.db中建立了一个表books。对这个表可以增加数据了。 >>> cur.execute('insert into books values ("from beginner to master", "laoqi", "python")') 为了保证数据能够保存,还要如下操作(这是多么熟悉的操作流程和命令呀): >>> conn.commit() >>> cur.close() >>> conn.close() 在刚才建立的那个数据库中,已经有了一个表books,表中已经有了一条记录。 ###查询 存进去了,总要看看,这算强迫症吗? >>> conn = sqlite3.connect("23301.db") >>> cur = conn.cursor() >>> cur.execute('select * from books') >>> print cur.fetchall() #Python 3: print(cur.fetchall()) [(u'from beginner to master', u'laoqi', u'python')] ###批量插入 多增加点内容,以便于做别的操作: >>> books = [("first book","first","c"), ("second book","second","c"), ("third book","second","python")] 这回来一个批量插入: >>> cur.executemany('insert into books values (?,?,?)', books) >>> conn.commit() 用循环语句打印查询结果: >>> rows = cur.execute('select * from books') >>> for row in rows: ... print row #Python 3: print(row) ... (u'from beginner to master', u'laoqi', u'python') (u'first book', u'first', u'c') (u'second book', u'second', u'c') (u'third book', u'second', u'python') ###更新 正如前面所说,在`cur.execute()`中,你可以写SQL语句来操作数据库。 >>> cur.execute("update books set title='physics' where author='first'") >>> conn.commit() 按照条件查处来看一看: >>> cur.execute("select * from books where author='first'") >>> cur.fetchone() (u'physics', u'first', u'c') ###删除 删除也是操作数据库必须的动作。 >>> cur.execute("delete from books where author='second'") >>> conn.commit() >>> cur.execute("select * from books") >>> cur.fetchall() [(u'from beginner to master', u'laoqi', u'python'), (u'physics', u'first', u'c')] 不要忘记,在完成对数据库的操作后,一定要关门才能走人: >>> cur.close() >>> conn.close() 基本知识已经介绍差不多了。当然,在实践的编程中,或许会遇到问题,就请读者多参考官方文档:[https://docs.python.org/2/library/sqlite3.html](https://docs.python.org/2/library/sqlite3.html) ------ [总目录](./index.md)   |   [上节:MongoDB数据库](./232.md)   |   [下节:电子表格](./234.md) 如果你认为有必要打赏我,请通过支付宝:**qiwsir@126.com**,不胜感激。
X Tutup