99999久久久久久亚洲,欧美人与禽猛交狂配,高清日韩av在线影院,一个人在线高清免费观看,啦啦啦在线视频免费观看www

熱線電話:13121318867

登錄
首頁精彩閱讀Python操作SQLite數(shù)據(jù)庫的方法詳解
Python操作SQLite數(shù)據(jù)庫的方法詳解
2017-10-10
收藏

Python操作SQLite數(shù)據(jù)庫的方法詳解

本文實例講述了Python操作SQLite數(shù)據(jù)庫的方法。分享給大家供大家參考,具體如下:

SQLite簡單介紹

SQLite數(shù)據(jù)庫是一款非常小巧的嵌入式開源數(shù)據(jù)庫軟件,也就是說沒有獨立的維護進程,所有的維護都來自于程序本身。它是遵守ACID的關(guān)聯(lián)式數(shù)據(jù)庫管理系統(tǒng),它的設(shè)計目標是嵌入式的,而且目前已經(jīng)在很多嵌入式產(chǎn)品中使用了它,它占用資源非常的低,在嵌入式設(shè)備中,可能只需要幾百K的內(nèi)存就夠了。它能夠支持Windows/Linux/Unix等等主流的操作系統(tǒng),同時能夠跟很多程序語言相結(jié)合,比如 Tcl、C#、PHP、Java等,還有ODBC接口,同樣比起Mysql、PostgreSQL這兩款開源世界著名的數(shù)據(jù)庫管理系統(tǒng)來講,它的處理速度比他們都快。SQLite第一個Alpha版本誕生于2000年5月. 至今已經(jīng)有10個年頭,SQLite也迎來了一個版本 SQLite 3已經(jīng)發(fā)布。

安裝與使用

1.導(dǎo)入Python SQLITE數(shù)據(jù)庫模塊
     Python2.5之后,內(nèi)置了SQLite3,成為了內(nèi)置模塊,這給我們省了安裝的功夫,只需導(dǎo)入即可~    
import sqlite3

2. 創(chuàng)建/打開數(shù)據(jù)庫

     在調(diào)用connect函數(shù)的時候,指定庫名稱,如果指定的數(shù)據(jù)庫存在就直接打開這個數(shù)據(jù)庫,如果不存在就新創(chuàng)建一個再打開。    
cx = sqlite3.connect("E:/test.db")

     也可以創(chuàng)建數(shù)據(jù)庫在內(nèi)存中。
    
con = sqlite3.connect(":memory:")

3.數(shù)據(jù)庫連接對象

    打開數(shù)據(jù)庫時返回的對象cx就是一個數(shù)據(jù)庫連接對象,它可以有以下操作:

① commit()--事務(wù)提交  
② rollback()--事務(wù)回滾  
③ close()--關(guān)閉一個數(shù)據(jù)庫連接  
④ cursor()--創(chuàng)建一個游標

    關(guān)于commit(),如果isolation_level隔離級別默認,那么每次對數(shù)據(jù)庫的操作,都需要使用該命令,你也可以設(shè)置isolation_level=None,這樣就變?yōu)樽詣犹峤荒J健?br />
4.使用游標查詢數(shù)據(jù)庫

我們需要使用游標對象SQL語句查詢數(shù)據(jù)庫,獲得查詢對象。 通過以下方法來定義一個游標。

cu=cx.cursor()

游標對象有以下的操作:

① execute()--執(zhí)行sql語句  
② executemany--執(zhí)行多條sql語句  
③ close()--關(guān)閉游標  
④ fetchone()--從結(jié)果中取一條記錄,并將游標指向下一條記錄  
⑤ fetchmany()--從結(jié)果中取多條記錄  
⑥ fetchall()--從結(jié)果中取出所有記錄  
⑦ scroll()--游標滾動

1. 建表

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

上面語句創(chuàng)建了一個叫catalog的表,它有一個主鍵id,一個pid,和一個name,name是不可以重復(fù)的,以及一個nickname默認為NULL。

2. 插入數(shù)據(jù)

請注意避免以下寫法:    
# Never do this -- insecure 會導(dǎo)致注入攻擊
pid=200
c.execute("... where pid = '%s'" % pid)

正確的做法如下,如果t只是單個數(shù)值,也要采用t=(n,)的形式,因為元組是不可變的。    
for t in[(0,10,'abc','Yu'),(1,20,'cba','Xu')]:
  cx.execute("insert into catalog values (?,?,?,?)", t)

簡單的插入兩行數(shù)據(jù),不過需要提醒的是,只有提交了之后,才能生效.我們使用數(shù)據(jù)庫連接對象cx來進行提交commit和回滾rollback操作.    
cx.commit()

3.查詢    
cu.execute("select * from catalog")

要提取查詢到的數(shù)據(jù),使用游標的fetch函數(shù),如:    
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()

注意,修改數(shù)據(jù)以后提交

5.刪除    
cu.execute("delete from catalog where id = 1")
cx.commit()

6.使用中文

請先確定你的IDE或者系統(tǒng)默認編碼是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提供了基于索引和基于名字大小寫敏感的方式來訪問列而幾乎沒有內(nèi)存開銷。 原文如下:

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]:
In [33]: r = c.fetchone()
In [34]: type(r)
Out[34]:
In [35]: r
Out[35]:
In [36]: print r
(0, 10, u'\u9c7c', u'Yu')
In [37]: len(r)
Out[37]: 4
In [39]: r[2]      #使用索引查詢
Out[39]: u'\u9c7c'
In [41]: r.keys()
Out[41]: ['id', 'pid', 'name', 'nickname']
In [42]: for e in r:
  ....:   print e,
  ....:
0 10 魚 Yu

使用列的關(guān)鍵詞查詢    
In [43]: r['id']
Out[43]: 0
In [44]: r['name']
Out[44]: u'\u9c7c'

數(shù)據(jù)分析咨詢請掃描二維碼

若不方便掃碼,搜微信號:CDAshujufenxi

數(shù)據(jù)分析師資訊
更多

OK
客服在線
立即咨詢
客服在線
立即咨詢
') } function initGt() { var handler = function (captchaObj) { captchaObj.appendTo('#captcha'); captchaObj.onReady(function () { $("#wait").hide(); }).onSuccess(function(){ $('.getcheckcode').removeClass('dis'); $('.getcheckcode').trigger('click'); }); window.captchaObj = captchaObj; }; $('#captcha').show(); $.ajax({ url: "/login/gtstart?t=" + (new Date()).getTime(), // 加隨機數(shù)防止緩存 type: "get", dataType: "json", success: function (data) { $('#text').hide(); $('#wait').show(); // 調(diào)用 initGeetest 進行初始化 // 參數(shù)1:配置參數(shù) // 參數(shù)2:回調(diào),回調(diào)的第一個參數(shù)驗證碼對象,之后可以使用它調(diào)用相應(yīng)的接口 initGeetest({ // 以下 4 個配置參數(shù)為必須,不能缺少 gt: data.gt, challenge: data.challenge, offline: !data.success, // 表示用戶后臺檢測極驗服務(wù)器是否宕機 new_captcha: data.new_captcha, // 用于宕機時表示是新驗證碼的宕機 product: "float", // 產(chǎn)品形式,包括:float,popup width: "280px", https: true // 更多配置參數(shù)說明請參見:http://docs.geetest.com/install/client/web-front/ }, handler); } }); } function codeCutdown() { if(_wait == 0){ //倒計時完成 $(".getcheckcode").removeClass('dis').html("重新獲取"); }else{ $(".getcheckcode").addClass('dis').html("重新獲取("+_wait+"s)"); _wait--; setTimeout(function () { codeCutdown(); },1000); } } function inputValidate(ele,telInput) { var oInput = ele; var inputVal = oInput.val(); var oType = ele.attr('data-type'); var oEtag = $('#etag').val(); var oErr = oInput.closest('.form_box').next('.err_txt'); var empTxt = '請輸入'+oInput.attr('placeholder')+'!'; var errTxt = '請輸入正確的'+oInput.attr('placeholder')+'!'; var pattern; if(inputVal==""){ if(!telInput){ errFun(oErr,empTxt); } return false; }else { switch (oType){ case 'login_mobile': pattern = /^1[3456789]\d{9}$/; if(inputVal.length==11) { $.ajax({ url: '/login/checkmobile', type: "post", dataType: "json", data: { mobile: inputVal, etag: oEtag, page_ur: window.location.href, page_referer: document.referrer }, success: function (data) { } }); } break; case 'login_yzm': pattern = /^\d{6}$/; break; } if(oType=='login_mobile'){ } if(!!validateFun(pattern,inputVal)){ errFun(oErr,'') if(telInput){ $('.getcheckcode').removeClass('dis'); } }else { if(!telInput) { errFun(oErr, errTxt); }else { $('.getcheckcode').addClass('dis'); } return false; } } return true; } function errFun(obj,msg) { obj.html(msg); if(msg==''){ $('.login_submit').removeClass('dis'); }else { $('.login_submit').addClass('dis'); } } function validateFun(pat,val) { return pat.test(val); }