Python查詢oracle數據庫速度慢的解決方案
如下所示:
conn = cx_Oracle.connect(’username/password@ip:port/servername’)cur = conn.cursor()cur.execute(’SELECT * FROM 'db'.'table'’)
cur是一個迭代器,不要用fetchall一次性取完數據
直接 for row in cur 即可取數據
使用:sqlalchemyMySQL-Python mysql+mysqldb://<user>:<password>@<host>[:<port>]/<dbname> pymysql mysql+pymysql://<username>:<password>@<host>/<dbname>[?<options>] MySQL-Connector mysql+mysqlconnector://<user>:<password>@<host>[:<port>]/<dbname> cx_Oracle oracle+cx_oracle://user:pass@host:port/dbname[?key=value&key=value...]
create_engine(’oracle+cx_oracle://{a}:@{c}:wyw2q2k/?service_name={e}’.format(a,b,c,d,e))create_engine(’mysql+pymysql://%(user)s:%(password)s@%(host)s/%(database)s?charset=utf8’ % laoshifu_info) df = pd.read_sql_table(table_name='table_name', con=engine) (the function to_sql is case-sensitive,Found the root cause from DBMS (mysql) autoconvert the table name to lowercase.)df = pd.read_sql_query(sql=sql,con=engine) # 很慢ordf = pd.read_sql('SELECT * FROM db.table ',engine,chunksize=50000)dflist = []for chunk in ordf: dflist.append(chunk)df = pd.concat(dflist)
補充:Python3 Cx_oracle 的一些使用技巧
Cx_oracle的一些使用技巧工作中的數據庫采用oracle。訪問oracle數據庫一般都采用cx_oracle包來完成,API很清晰,操作效率也比較高,而且oracle官方好像對cx_oracle也非常支持,提供了豐富的文檔。這里討論一些使用技巧,作為記錄,可能對你也有用。
我最近用python寫了一個小工具,這個工具根據客戶端的請求查詢數據庫,并將結果集以json的方式返回。請求的格式如下:
{fields : [ {name : 'project_id', type : 'string'}, {name : 'project_name', type : 'string'}],sql : 'select t.project_id, t.project_name from dp_project t' }
即,客戶端描述自己想要的元數據信息(字段名稱,字段類型),以及SQL語句,服務器端根據此信息查詢數據庫,并將返回組織成客戶端在fields中描述的那樣。
cx_oracle默認從cursor中fetch出來的數據是一個元組,按照SQL中的順序組織,但是我希望返回的是一個字典結構,這個可以通過設置cursor的rowfactory屬性來實現,定義一個rowfactory的回調函數:
def makedict(self, cursor):cols = [d[0] for d in cursor.description] def createrow(*args): return dict(zip(cols, args)) return createrow
這個函數返回一個函數:createrow??赡苡悬c繞口,仔細想想就清晰了。cursor中帶有足夠的信息來生成這個字典,如cursor的description的值為:
[ (’PROJECT_ID’, <;type ’cx_Oracle.STRING’>, 40, 40, 0, 0, 0), (’PROJECT_NAME’, <;type ’cx_Oracle.STRING’>, 50, 50, 0, 0, 1) ]
我們需要的是cursor.description的第一列,zip函數將cols和默認的那個元組合成為一個新的元組,再用dict轉換為一個新的字典對象返回。
然后將這個返回函數的函數注冊給cursor的rowfactory即可:
cursor.rowfactory = self.makedict(cursor)
這樣,我們使用cursor.fetchall/fetchone的時候,取出來的就成為一個字典對象,很方便將其序列化為json格式返回。
另一個技巧是關于將查詢到的結果中,字符串類型的字段轉換為unicode,數值類型的不做處理:
def outtypehandler(self, cursor, name, dtype, size, p, s):if dtype in (oracle.STRING, oracle.FIXED_CHAR): return cursor.var(unicode, size, cursor.arraysize)
將connection對象的outputtypehandler注冊為此函數即可:
connection = oracle.connect(self.constr) connection.outputtypehandler = self.outtypehandler
通用查詢的這個小工具還在開發中,等完成了再整理一下。
以上為個人經驗,希望能給大家一個參考,也希望大家多多支持好吧啦網。如有錯誤或未考慮完全的地方,望不吝賜教。
相關文章:
