GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing raw.githubusercontent.com — raw.githubusercontent.com >然而,敬虔加上知足的心便是大利了,因为我们没有带什么到世上来,也不能带什么去,只要有衣有食,就当知足。但那些想要发财的人,就陷在迷惑、落在网罗和许多无知有害的私欲里,叫人沉在败坏和灭亡中。贪财是万恶之根。有人贪恋钱财,就被引诱离了真道,用许多愁苦把自己刺透了。(1 TIMOTHY 6:6-10)
#SQLite数据库
SQLite是一个小型的关系型数据库,它最大的特点在于不需要服务器、零配置。在前面的两个服务器,不管是MySQL还是MongoDB,都需要“安装”,安装之后,它运行起来,其实是已经有一个相应的服务器在跑着呢。而SQLite不需要这样,首先python已经将相应的驱动模块作为标准库一部分了,只要安装了python,就可以使用;另外,它也不需要服务器,可以类似操作文件那样来操作SQLite数据库文件。还有一点也不错,SQLite源代码不受版权限制。
SQLite也是一个关系型数据库,所以SQL语句,都可以在里面使用。
跟操作mysql数据库类似,对于SQLite数据库,也要通过以下几步:
- 建立连接对象
- 连接对象方法:建立游标对象
- 游标对象方法:执行sql语句
##建立连接对象
由于SQLite数据库的驱动已经在python里面了,所以,只要引用就可以直接使用
>>> 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()`
###创建数据库表
在mysql中,我们演示的是利用mysql的shell来创建的表。其实,当然可以使用sql语句,在python中实现这个功能。这里对sqlite数据库,就如此操作一番。
>>> create_table = "create table books (title text, author text, lang text) "
>>> cur.execute(create_table)
|
| You are visitor 01402792 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |