SQLite是一個小型的關系型數據庫,它最大的特點在于不需要服務器、零配置。在前面的兩個服務器,不管是MySQL還是MongoDB,都需要“安裝”,安裝之后,它運行起來,其實是已經有一個相應的服務器在跑著呢。而SQLite不需要這樣,首先python已經將相應的驅動模塊作為標準庫一部分了,只要安裝了python,就可以使用;另外,它也不需要服務器,可以類似操作文件那樣來操作SQLite數據庫文件。還有一點也不錯,SQLite源代碼不受版權限制。
SQLite也是一個關系型數據庫,所以SQL語句,都可以在里面使用。
跟操作mysql數據庫類似,對于SQLite數據庫,也要通過以下幾步:
* 建立連接對象
* 連接對象方法:建立游標對象
* 游標對象方法:執行sql語句
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#建立連接對象)建立連接對象
由于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']
~~~
## [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#游標對象)游標對象
這步跟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()`
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#創建數據庫表)創建數據庫表
在mysql中,我們演示的是利用mysql的shell來創建的表。其實,當然可以使用sql語句,在python中實現這個功能。這里對sqlite數據庫,就如此操作一番。
~~~
>>> create_table = "create table books (title text, author text, lang text) "
>>> cur.execute(create_table)
<sqlite3.Cursor object at 0xb73ed5a0>
~~~
這樣就在數據庫23301.db中建立了一個表books。對這個表可以增加數據了:
~~~
>>> cur.execute('insert into books values ("from beginner to master", "laoqi", "python")')
<sqlite3.Cursor object at 0xb73ed5a0>
~~~
為了保證數據能夠保存,還要(這是多么熟悉的操作流程和命令呀):
~~~
>>> conn.commit()
>>> cur.close()
>>> conn.close()
~~~
支持,剛才建立的那個數據庫中,已經有了一個表books,表中已經有了一條記錄。
整個流程都不陌生。
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#查詢)查詢
存進去了,總要看看,這算強迫癥嗎?
~~~
>>> conn = sqlite3.connect("23301.db")
>>> cur = conn.cursor()
>>> cur.execute('select * from books')
<sqlite3.Cursor object at 0xb73edea0>
>>> print cur.fetchall()
[(u'from beginner to master', u'laoqi', u'python')]
~~~
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#批量插入)批量插入
多增加點內容,以便于做別的操作:
~~~
>>> books = [("first book","first","c"), ("second book","second","c"), ("third book","second","python")]
~~~
這回來一個批量插入
~~~
>>> cur.executemany('insert into books values (?,?,?)', books)
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()
~~~
用循環語句打印一下查詢結果:
~~~
>>> rows = cur.execute('select * from books')
>>> for row in rows:
... 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')
~~~
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#更新)更新
正如前面所說,在cur.execute()中,你可以寫SQL語句,來操作數據庫。
~~~
>>> cur.execute("update books set title='physics' where author='first'")
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()
~~~
按照條件查處來看一看:
~~~
>>> cur.execute("select * from books where author='first'")
<sqlite3.Cursor object at 0xb73edea0>
>>> cur.fetchone()
(u'physics', u'first', u'c')
~~~
### [](https://github.com/qiwsir/StarterLearningPython/blob/master/233.md#刪除)刪除
在sql語句中,這也是常用的。
~~~
>>> cur.execute("delete from books where author='second'")
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()
>>> cur.execute("select * from books")
<sqlite3.Cursor object at 0xb73edea0>
>>> 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)
- 第零章 預備
- 關于Python的故事
- 從小工到專家
- Python安裝
- 集成開發環境
- 第壹章 基本數據類型
- 數和四則運算
- 除法
- 常用數學函數和運算優先級
- 寫一個簡單的程序
- 字符串(1)
- 字符串(2)
- 字符串(3)
- 字符串(4)
- 字符編碼
- 列表(1)
- 列表(2)
- 列表(3)
- 回顧list和str
- 元組
- 字典(1)
- 字典(2)
- 集合(1)
- 集合(2)
- 第貳章 語句和文件
- 運算符
- 語句(1)
- 語句(2)
- 語句(3)
- 語句(4)
- 語句(5)
- 文件(1)
- 文件(2)
- 迭代
- 練習
- 自省
- 第叁章 函數
- 函數(1)
- 函數(2)
- 函數(3)
- 函數(4)
- 函數練習
- 第肆章 類
- 類(1)
- 類(2)
- 類(3)
- 類(4)
- 類(5)
- 多態和封裝
- 特殊方法(1)
- 特殊方法(2)
- 迭代器
- 生成器
- 上下文管理器
- 第伍章 錯誤和異常
- 錯誤和異常(1)
- 錯誤和異常(2)
- 錯誤和異常(3)
- 第陸章 模塊
- 編寫模塊
- 標準庫(1)
- 標準庫(2)
- 標準庫(3)
- 標準庫(4)
- 標準庫(5)
- 標準庫(6)
- 標準庫(7)
- 標準庫(8)
- 第三方庫
- 第柒章 保存數據
- 將數據存入文件
- mysql數據庫(1)
- MySQL數據庫(2)
- mongodb數據庫(1)
- SQLite數據庫
- 電子表格
- 第捌章 用Tornado做網站
- 為做網站而準備
- 分析Hello
- 用tornado做網站(1)
- 用tornado做網站(2)
- 用tornado做網站(3)
- 用tornado做網站(4)
- 用tornado做網站(5)
- 用tornado做網站(6)
- 用tornado做網站(7)
- 第玖章 科學計算
- 為計算做準備
- Pandas使用(1)
- Pandas使用(2)
- 處理股票數據
- 附:網絡文摘
- 如何成為Python高手
- ASCII、Unicode、GBK和UTF-8字符編碼的區別聯系