python torndb模組安裝使用樣本

來源:互聯網
上載者:User

一、torndb概述
torndb是一個輕量級的基於MySQLdb封裝的一個模組,其是tornado架構的一部分。其項目首頁為:https://github.com/bdarnell/torndb 。從tornado3.0版本以後,其已經作為一個獨立模組發行了。可以通過easy_install 或pip的方式直接安裝。

二、串連與查詢
1、建立串連

import torndb
db = torndb.Connection("127.0.0.1:3306", "test", user="root", password="admin")
預設字元集UTF8,沒必要在加上 charset = "utf8" 。另外需要注意的是其預設時區為time_zone='+0:00',這個可以手動在串連的時候指定為東8區。

2、查詢

在MySQLdb中所有的操作都是通過execute執行的,而把TA封裝之後的torndb,提供了3種,execute,get,query。execute的樣本:

 代碼如下 複製代碼

cre='create table blog(id int,content text)'
db.execute(cre)
string='wawuee'
exe='insert into blog(id,content)values(%d,"%s")'%(1,string)
db.execute(exe)
execute包括建立表,插入表,刪除表等等,另外其也單獨封裝了insert、insertmany、update、updatemany函數,同時除了一般的execute函數,其還有execute_lastrowid、execute_rowcount、executemany、executemany_lastrowid、executemany_rowcount函數。

query與get

兩個都是用於返回資料結果,不同的是query可以返回多條結果;get查詢的結果為空白時,返回None,返回多於一條結果時會報出一個異常,一般只用於只有一條結果返回的情況。

 代碼如下 複製代碼

//query查詢
>>>sql = 'SELECT * FROM test WHERE name = %s AND id < %s'
>>>db.query(sql, 'bbb', 11)
[{'date': None, 'id': 1L, 'name': u'bbb'}, {'date': None, 'id': 2L, 'name': u'bbb'}]
//get查詢
>>>sql = 'SELECT * FROM test WHERE id = %s'
>>>db.get(sql, 2)
{'date': None, 'id': 2L, 'name': u'bbb'}
query查詢時,結果為多行時為list列表,單行只為字典。

insert與insertmany

 代碼如下 複製代碼

>>>sql = "INSERT INTO test (id,name,date) VALUES (%s,%s,%s)"
>>>db.insert(sql, 100, "aaa", '0000-01-01')
100L
insert的參數不支援列表或元組,如果想插入列表或元組的話可以用insertmany

#插入單行記錄
sql = "INSERT INTO test (id,name,date) VALUES (%s,%s,%s)"
db.insertmany(sql,[[200,'bbb',None]])
200L
#插入多行記錄
db.insertmany(sql,[[300,'bbb',None],[400,'bbb',None]])
400L
db.insertmany(sql,[(301,'bbb',None),(401,'bbb',None)])
401L

總結下,torndb對MySQLdb封裝後,query,get返回是list,dict這些,非常方便,可以直接拿來用,這是TA的優點,而且是預設自動commit的,不用MySQLdb的手動commit,用起來很是簡潔

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.