SQLite數(shù)據(jù)庫

2018-02-24 15:48 更新

SQLite是一個(gè)小型的關(guān)系型數(shù)據(jù)庫,它最大的特點(diǎn)在于不需要服務(wù)器、零配置。在前面的兩個(gè)服務(wù)器,不管是MySQL還是MongoDB,都需要“安裝”,安裝之后,它運(yùn)行起來,其實(shí)是已經(jīng)有一個(gè)相應(yīng)的服務(wù)器在跑著呢。而SQLite不需要這樣,首先python已經(jīng)將相應(yīng)的驅(qū)動(dòng)模塊作為標(biāo)準(zhǔn)庫一部分了,只要安裝了python,就可以使用;另外,它也不需要服務(wù)器,可以類似操作文件那樣來操作SQLite數(shù)據(jù)庫文件。還有一點(diǎn)也不錯(cuò),SQLite源代碼不受版權(quán)限制。

SQLite也是一個(gè)關(guān)系型數(shù)據(jù)庫,所以SQL語句,都可以在里面使用。

跟操作mysql數(shù)據(jù)庫類似,對(duì)于SQLite數(shù)據(jù)庫,也要通過以下幾步:

  • 建立連接對(duì)象
  • 連接對(duì)象方法:建立游標(biāo)對(duì)象
  • 游標(biāo)對(duì)象方法:執(zhí)行sql語句

建立連接對(duì)象

由于SQLite數(shù)據(jù)庫的驅(qū)動(dòng)已經(jīng)在python里面了,所以,只要引用就可以直接使用

>>> import sqlite3
>>> conn = sqlite3.connect("23301.db")

這樣就得到了連接對(duì)象,是不是比mysql連接要簡(jiǎn)化了很多呢。在sqlite3.connect("23301.db")語句中,如果已經(jīng)有了那個(gè)數(shù)據(jù)庫,就連接上它;如果沒有,就新建一個(gè)。注意,這里的路徑可以隨意指定的。

不妨到目錄中看一看,是否存在了剛才建立的數(shù)據(jù)庫文件。

/2code$ ls 23301.db
23301.db

果然有了一個(gè)文件。

連接對(duì)象建立起來之后,就要使用連接對(duì)象的方法繼續(xù)工作了。

>>> 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']

游標(biāo)對(duì)象

這步跟mysql也類似,要建立游標(biāo)對(duì)象。

>>> cur = conn.cursor()

接下來對(duì)數(shù)據(jù)庫內(nèi)容的操作,都是用游標(biāo)對(duì)象方法來實(shí)現(xiàn)了:

>>> 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()

創(chuàng)建數(shù)據(jù)庫表

在mysql中,我們演示的是利用mysql的shell來創(chuàng)建的表。其實(shí),當(dāng)然可以使用sql語句,在python中實(shí)現(xiàn)這個(gè)功能。這里對(duì)sqlite數(shù)據(jù)庫,就如此操作一番。

>>> create_table = "create table books (title text, author text, lang text) "
>>> cur.execute(create_table)
<sqlite3.Cursor object at 0xb73ed5a0>

這樣就在數(shù)據(jù)庫23301.db中建立了一個(gè)表books。對(duì)這個(gè)表可以增加數(shù)據(jù)了:

>>> cur.execute('insert into books values ("from beginner to master", "laoqi", "python")')
<sqlite3.Cursor object at 0xb73ed5a0>

為了保證數(shù)據(jù)能夠保存,還要(這是多么熟悉的操作流程和命令呀):

>>> conn.commit()
>>> cur.close()
>>> conn.close()

支持,剛才建立的那個(gè)數(shù)據(jù)庫中,已經(jīng)有了一個(gè)表books,表中已經(jīng)有了一條記錄。

整個(gè)流程都不陌生。

查詢

存進(jìn)去了,總要看看,這算強(qiáng)迫癥嗎?

>>> 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')]

批量插入

多增加點(diǎn)內(nèi)容,以便于做別的操作:

>>> books = [("first book","first","c"), ("second book","second","c"), ("third book","second","python")]

這回來一個(gè)批量插入

>>> cur.executemany('insert into books values (?,?,?)', books)
<sqlite3.Cursor object at 0xb73edea0>
>>> conn.commit()

用循環(huán)語句打印一下查詢結(jié)果:

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

更新

正如前面所說,在cur.execute()中,你可以寫SQL語句,來操作數(shù)據(jù)庫。

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

刪除

在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')]

不要忘記,在你完成對(duì)數(shù)據(jù)庫的操作是,一定要關(guān)門才能走人:

>>> cur.close()
>>> conn.close()

作為基本知識(shí),已經(jīng)介紹差不多了。當(dāng)然,在實(shí)踐的編程中,或許會(huì)遇到問題,就請(qǐng)讀者多參考官方文檔:https://docs.python.org/2/library/sqlite3.html

以上內(nèi)容是否對(duì)您有幫助:
在線筆記
App下載
App下載

掃描二維碼

下載編程獅App

公眾號(hào)
微信公眾號(hào)

編程獅公眾號(hào)