python操作數(shù)據(jù)庫獲取結果之fetchone和fetchall的區(qū)別說明
每次使用python獲取查詢結果的時候,都會糾結一段時間到底用fetchone和fetchall,用不好容易報錯,關鍵在于沒有搞清楚它們之間的區(qū)別和使用場景。
fetchone與fetchall區(qū)別環(huán)境:python3中
fetchone不管查詢結果是多條數(shù)據(jù)還是單條數(shù)據(jù),使用fetchone得到的始終是一個元組。
如果查詢結果是單條數(shù)據(jù):fetchone得到的單條數(shù)據(jù)的元組;
如果查詢結果是多條數(shù)據(jù):fetchone默認是結果中的第一條數(shù)據(jù)構成的元組;
這就決定了如果需要取元組中的數(shù)值,需要使用cur.fetchone[0]
fetchall不管查詢結果是多條數(shù)據(jù)還是單條數(shù)據(jù),使用fetchall得到的始終是一個由元組組成的列表。
如果查詢結果是單條數(shù)據(jù):fetchall得到的是由單個元組組成的列表,列表內是有單條數(shù)據(jù)組成的元組,即列表包含元組;
如果查詢結果是多條數(shù)據(jù):fetchall得到的是由多個元組組成的列表;
這就決定了如果需要取元組中的數(shù)值,需要使用cur.fetchone[0][0]
使用場景一般來說,查詢結果集是單條數(shù)據(jù)的,使用fetchone獲取數(shù)據(jù)
一般來說,查詢結果集是多條數(shù)據(jù)的,使用fetchall獲取數(shù)據(jù)
簡單實例import cx_Oracleconn = cx_Oracle.connect('用戶名/密碼@數(shù)據(jù)庫地址')cur = conn.cursor()sql_3 = 'select id from CZEPT_BSDT t WHERE name=’{}’'.format('基本支出調劑')cur.execute(sql_3)result_3 = cur.fetchone() # 單條數(shù)據(jù)結果集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ù)結果集print(result_2) # [(1,’基本支出調劑’),(3,’銀行賬戶審批’),(5,’項目支出調劑’)]print(type(result_2)) # <class ’list’>result_2= result_2[0][0]print(result_2) # 1print(type(result_2)) # <class ’int’>注意事項
對于使用fetchone和fetchall獲取到的結果,最好使用之前先判斷非空,否則在存在空值的情況下獲取元組內的數(shù)據(jù)時,會報“超出索引”的異常。多次踩雷坑。
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() # 因為存在歸口處室為空,所以切片的時候總是報超出索引范圍,搞了好久 if result is not None:j[’DIVISIONGUID’] = str(result[0])
補充:python DB.fetchall()--獲取數(shù)據(jù)庫所有記錄列表
查詢到的數(shù)據(jù)格式為列表:
多個元素的列表:
單個元素的列表:
以上為個人經(jīng)驗,希望能給大家一個參考,也希望大家多多支持好吧啦網(wǎng)。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
