W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
SQLite是一個小型的關(guān)系型數(shù)據(jù)庫,它最大的特點在于不需要服務(wù)器、零配置。在前面的兩個服務(wù)器,不管是MySQL還是MongoDB,都需要“安裝”,安裝之后,它運行起來,其實是已經(jīng)有一個相應(yīng)的服務(wù)器在跑著呢。而SQLite不需要這樣,首先python已經(jīng)將相應(yīng)的驅(qū)動模塊作為標(biāo)準庫一部分了,只要安裝了python,就可以使用;另外,它也不需要服務(wù)器,可以類似操作文件那樣來操作SQLite數(shù)據(jù)庫文件。還有一點也不錯,SQLite源代碼不受版權(quán)限制。
SQLite也是一個關(guān)系型數(shù)據(jù)庫,所以SQL語句,都可以在里面使用。
跟操作mysql數(shù)據(jù)庫類似,對于SQLite數(shù)據(jù)庫,也要通過以下幾步:
由于SQLite數(shù)據(jù)庫的驅(qū)動已經(jīng)在python里面了,所以,只要引用就可以直接使用
>>> import sqlite3
>>> conn = sqlite3.connect("23301.db")
這樣就得到了連接對象,是不是比mysql連接要簡化了很多呢。在sqlite3.connect("23301.db")
語句中,如果已經(jīng)有了那個數(shù)據(jù)庫,就連接上它;如果沒有,就新建一個。注意,這里的路徑可以隨意指定的。
不妨到目錄中看一看,是否存在了剛才建立的數(shù)據(jù)庫文件。
/2code$ ls 23301.db
23301.db
果然有了一個文件。
連接對象建立起來之后,就要使用連接對象的方法繼續(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']
這步跟mysql也類似,要建立游標(biāo)對象。
>>> cur = conn.cursor()
接下來對數(shù)據(jù)庫內(nèi)容的操作,都是用游標(biāo)對象方法來實現(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()
在mysql中,我們演示的是利用mysql的shell來創(chuàng)建的表。其實,當(dāng)然可以使用sql語句,在python中實現(xiàn)這個功能。這里對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中建立了一個表books。對這個表可以增加數(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()
支持,剛才建立的那個數(shù)據(jù)庫中,已經(jīng)有了一個表books,表中已經(jī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')]
多增加點內(nèi)容,以便于做別的操作:
>>> 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()
用循環(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')]
不要忘記,在你完成對數(shù)據(jù)庫的操作是,一定要關(guān)門才能走人:
>>> cur.close()
>>> conn.close()
作為基本知識,已經(jīng)介紹差不多了。當(dāng)然,在實踐的編程中,或許會遇到問題,就請讀者多參考官方文檔:https://docs.python.org/2/library/sqlite3.html
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: