搜尋
首頁後端開發Python教學關於Python操作SQLite資料庫的方法步驟詳解

關於Python操作SQLite資料庫的方法步驟詳解

Jun 18, 2017 am 11:22 AM
pythonsqlite關於操作資料庫

這篇文章主要介紹了Python操作SQLite資料庫的方法,較為詳細的分析了Python安裝sqlite資料庫模組及針對sqlite資料庫的常用操作技巧,需要的朋友可以參考下

本文實例講述了Python操作SQLite資料庫的方法。分享給大家供大家參考,具體如下:

SQLite簡單介紹

SQLite資料庫是一款非常小巧的嵌入式開源資料庫軟體,也就是說沒有獨立的維護流程,所有的維護都來自於程式本身。它是遵守ACID的關聯式資料庫管理系統,它的設計目標是嵌入式的,而且目前已經在許多嵌入式產品中使用了它,它佔用資源非常的低,在嵌入式設備中,可能只需要幾百K的記憶體就夠了。它能夠支援Windows/Linux/Unix等等主流的作業系統,同時能夠跟很多程式語言結合,例如Tcl、C#、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的資料庫管理系統來講,它的處理速度比他們都快。 SQLite第一個Alpha版本誕生於2000年5月. 至今已經有10個年頭,SQLite也迎來了一個版本 SQLite 3已經發布。

安裝與使用

1.匯入Python SQLITE資料庫模組

     Python2.5之後,內建了SQLite3,成為了內建模組,這給我​​們省了安裝的功夫,只需導入即可~


import sqlite3

2. 建立/開啟資料庫

     在呼叫connect函數的時候,指定函式庫名稱,如果指定的資料庫存在就直接開啟這個資料庫,如果不存在就新建立一個再開啟。


cx = sqlite3.connect("E:/test.db")

     也可以在記憶體中建立資料庫


con = sqlite3.connect(":memory:")

3.資料庫連線對象

    開啟資料庫時回傳的物件cx就是一個資料庫連線對象,它可以有以下操作:

① commit()--事務提交  
② rollback()--事務回滾  
③ close()--關閉一個資料庫連線  
④ cursor()--建立一個遊標

    關於commit(),如果isolation_level隔離等級默認,那麼每次對資料庫的操作,都需要使用該指令,你也可以設定isolation_level=None,這樣就變成自動提交模式。

4.使用遊標查詢資料庫

我們需要使用遊標物件SQL語句查詢資料庫,取得查詢物件。 透過以下方法來定義一個遊標。

cu=cx.cursor()

遊標物件有以下的操作:

① execute()--執行sql語句  
② executemany--執行多個sql語句  
③ close()--關閉遊標  
④ fetchone()--從結果中取一筆記錄,並將遊標指向下一記錄  
⑤ fetchmany() --從結果中取多個記錄  
⑥ fetchall()--從結果中取出所有記錄  
⑦ scroll()--遊標滾動

1. 建表

複製程式碼 程式碼如下:

cu.execute("create table catalog (id integer primary key,pid integer,name varchar( 10) UNIQUE,nickname text NULL)")

上面語句建立了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重複的,以及一個nickname默認為NULL。

2. 插入資料

請注意避免以下寫法:


# Never do this -- insecure 会导致注入攻击
pid=200
c.execute("... where pid = '%s'" % pid)

正確的做法如下,如果t只是單一數值,也要採用t=(n,)的形式,因為元組是不可變的。


for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
  cx.execute("insert into catalog values (?,?,?,?)", t)

簡單的插入兩行資料,不過需要提醒的是,只有提交了之後,才能生效.我們使用資料庫連接物件cx來進行提交commit和回滾rollback操作.


cx.commit()

3.查詢


cu.execute("select * from catalog")

要提取查詢到的數據,使用遊標的fetch函數,如:


In [10]: cu.fetchall()
Out[10]: [(0, 10, u'abc', u'Yu'), (1, 20, u'cba', u'Xu')]

如果我們使用cu.fetchone(),則先傳回清單中的第一項,再次使用,則傳回第二項,依序下去.

4.修改


#
In [12]: cu.execute("update catalog set name='Boy' where id = 0")
In [13]: cx.commit()

注意,修改資料以後提交



################# ##5.刪除###############
cu.execute("delete from catalog where id = 1") 
cx.commit()
######6.使用中文#########請先確定你的IDE或系統預設編碼是utf-8,並且在中文前加上u#############
x=u'鱼'
cu.execute("update catalog set name=? where id = 0",x)
cu.execute("select * from catalog")
cu.fetchall()
[(0, 10, u'\u9c7c', u'Yu'), (1, 20, u'cba', u'Xu')]

如果要显示出中文字体,那需要依次打印出每个字符串


In [26]: for item in cu.fetchall():
  ....:   for element in item:
  ....:     print element,
  ....:   print
  ....: 
0 10 鱼 Yu
1 20 cba Xu

7.Row类型

Row提供了基于索引和基于名字大小写敏感的方式来访问列而几乎没有内存开销。 原文如下:

sqlite3.Row provides both index-based and case-insensitive name-based access to columns with almost no memory overhead. It will probably be better than your own custom dictionary-based approach or even a db_row based solution.

Row对象的详细介绍

class sqlite3.Row
A Row instance serves as a highly optimized row_factory for Connection objects. It tries to mimic a tuple in most of its features.
It supports mapping access by column name and index, iteration, representation, equality testing and len().
If two Row objects have exactly the same columns and their members are equal, they compare equal.
Changed in version 2.6: Added iteration and equality (hashability).
keys()
This method returns a tuple of column names. Immediately after a query, it is the first member of each tuple in Cursor.description.
New in version 2.6.

下面举例说明


In [30]: cx.row_factory = sqlite3.Row
In [31]: c = cx.cursor()
In [32]: c.execute('select * from catalog')
Out[32]: <sqlite3.Cursor object at 0x05666680>
In [33]: r = c.fetchone()
In [34]: type(r)
Out[34]: <type &#39;sqlite3.Row&#39;>
In [35]: r
Out[35]: <sqlite3.Row object at 0x05348980>
In [36]: print r
(0, 10, u&#39;\u9c7c&#39;, u&#39;Yu&#39;)
In [37]: len(r)
Out[37]: 4
In [39]: r[2]      #使用索引查询
Out[39]: u&#39;\u9c7c&#39;
In [41]: r.keys()
Out[41]: [&#39;id&#39;, &#39;pid&#39;, &#39;name&#39;, &#39;nickname&#39;]
In [42]: for e in r:
  ....:   print e,
  ....: 
0 10 鱼 Yu

使用列的关键词查询


In [43]: r[&#39;id&#39;]
Out[43]: 0
In [44]: r[&#39;name&#39;]
Out[44]: u&#39;\u9c7c&#39;

以上是關於Python操作SQLite資料庫的方法步驟詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

禪工作室 13.0.1

禪工作室 13.0.1

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

MantisBT

MantisBT

Mantis是一個易於部署的基於Web的缺陷追蹤工具,用於幫助產品缺陷追蹤。它需要PHP、MySQL和一個Web伺服器。請查看我們的演示和託管服務。

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

SublimeText3 英文版

SublimeText3 英文版

推薦:為Win版本,支援程式碼提示!