python操作數(shù)據(jù)庫獲取結(jié)果之fetchone和fetchall的區(qū)別說明
每次使用python獲取查詢結(jié)果的時(shí)候,都會(huì)糾結(jié)一段時(shí)間到底用fetchone和fetchall,用不好容易報(bào)錯(cuò),關(guān)鍵在于沒有搞清楚它們之間的區(qū)別和使用場(chǎng)景。
fetchone與fetchall區(qū)別環(huán)境:python3中
fetchone不管查詢結(jié)果是多條數(shù)據(jù)還是單條數(shù)據(jù),使用fetchone得到的始終是一個(gè)元組。
如果查詢結(jié)果是單條數(shù)據(jù):fetchone得到的單條數(shù)據(jù)的元組;
如果查詢結(jié)果是多條數(shù)據(jù):fetchone默認(rèn)是結(jié)果中的第一條數(shù)據(jù)構(gòu)成的元組;
這就決定了如果需要取元組中的數(shù)值,需要使用cur.fetchone[0]
fetchall不管查詢結(jié)果是多條數(shù)據(jù)還是單條數(shù)據(jù),使用fetchall得到的始終是一個(gè)由元組組成的列表。
如果查詢結(jié)果是單條數(shù)據(jù):fetchall得到的是由單個(gè)元組組成的列表,列表內(nèi)是有單條數(shù)據(jù)組成的元組,即列表包含元組;
如果查詢結(jié)果是多條數(shù)據(jù):fetchall得到的是由多個(gè)元組組成的列表;
這就決定了如果需要取元組中的數(shù)值,需要使用cur.fetchone[0][0]
使用場(chǎng)景一般來說,查詢結(jié)果集是單條數(shù)據(jù)的,使用fetchone獲取數(shù)據(jù)
一般來說,查詢結(jié)果集是多條數(shù)據(jù)的,使用fetchall獲取數(shù)據(jù)
簡(jiǎn)單實(shí)例import cx_Oracleconn = cx_Oracle.connect('用戶名/密碼@數(shù)據(jù)庫地址')cur = conn.cursor()sql_3 = 'select id from CZEPT_BSDT t WHERE name=’{}’'.format('基本支出調(diào)劑')cur.execute(sql_3)result_3 = cur.fetchone() # 單條數(shù)據(jù)結(jié)果集print(result_3) # (1,)print(type(result_3)) # <class ’tuple’>result_3= result_3[0] print(result_3) # 1print(type(result_3)) # <class ’int’>print('*' * 50)sql_2 = 'select * from CZEPT_BSDT ' cur.execute(sql_2)result_2 = cur.fetchall() # 多條數(shù)據(jù)結(jié)果集print(result_2) # [(1,’基本支出調(diào)劑’),(3,’銀行賬戶審批’),(5,’項(xiàng)目支出調(diào)劑’)]print(type(result_2)) # <class ’list’>result_2= result_2[0][0]print(result_2) # 1print(type(result_2)) # <class ’int’>注意事項(xiàng)
對(duì)于使用fetchone和fetchall獲取到的結(jié)果,最好使用之前先判斷非空,否則在存在空值的情況下獲取元組內(nèi)的數(shù)據(jù)時(shí),會(huì)報(bào)“超出索引”的異常。多次踩雷坑。
import cx_Oracleconnection = cx_Oracle.connect(’用戶名/密碼@數(shù)據(jù)庫地址’)cur = connection.cursor()for j in data_list: sql = 'select guid from jczl.division where name=’{}’'.format(j[’DIVISIONNAME’]) cur.execute(sql) result = cur.fetchone() # 因?yàn)榇嬖跉w口處室為空,所以切片的時(shí)候總是報(bào)超出索引范圍,搞了好久 if result is not None:j[’DIVISIONGUID’] = str(result[0])
補(bǔ)充:python DB.fetchall()--獲取數(shù)據(jù)庫所有記錄列表
查詢到的數(shù)據(jù)格式為列表:
多個(gè)元素的列表:
單個(gè)元素的列表:
以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持好吧啦網(wǎng)。如有錯(cuò)誤或未考慮完全的地方,望不吝賜教。
相關(guān)文章:
1. JAMon(Java Application Monitor)備忘記2. Python 的 __str__ 和 __repr__ 方法對(duì)比3. Java8內(nèi)存模型PermGen Metaspace實(shí)例解析4. IntelliJ IDEA設(shè)置背景圖片的方法步驟5. Spring security 自定義過濾器實(shí)現(xiàn)Json參數(shù)傳遞并兼容表單參數(shù)(實(shí)例代碼)6. IntelliJ IDEA設(shè)置默認(rèn)瀏覽器的方法7. 學(xué)python最電腦配置有要求么8. 基于python實(shí)現(xiàn)操作git過程代碼解析9. Python OpenCV去除字母后面的雜線操作10. 增大python字體的方法步驟
