Pandas cx_Oracle使用方法

正确安装好cx_oracle之后,要使用它来连接到oracle数据库进行操作,具体应该分3步走:

第一步:导入cx_Oracle,建立连接

>>>  import cx_Oracle      #导入模块
>>>  db = cx_Oracle.connect('hr', 'hrpwd', 'localhost:1521/XE') 建立连接,3个参数分开写
特别注意:这里的 'localhost:1521/XE'可以是你oracle net manager配置的链接名,如oracl,我就是在这里耽搁了半天

>>>  db1 = cx_Oracle.connect('hr/hrpwd@localhost:1521/XE') 建立连接,3个参数连写
>>>  dsn_tns = cx_Oracle.makedsn('localhost', 1521, 'XE')
>>>  print dsn_tns
(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=localhost)(PORT=1521)))
(CONNECT_DATA=(SID=XE)))
>>>  db2 = cx_Oracle.connect('hr', 'hrpwd', dsn_tns)
>>> <strong style="line-height: normal;">print db.version</strong><br style="line-height: normal;" />
10.2.0.1.0<br style="line-height: normal;" />
>>> <strong style="line-height: normal;">versioning = db.version.split('.')</strong><br style="line-height: normal;" />
>>> <strong style="line-height: normal;">print versioning</strong><br style="line-height: normal;" />
['10', '2', '0', '1', '0']<br style="line-height: normal;" />
>>> <strong style="line-height: normal;">if versioning[0]=='10':</strong><br style="line-height: normal;" />
...       <strong style="line-height: normal;">print "Running 10g"</strong><br style="line-height: normal;" />
... <strong style="line-height: normal;">elif versioning[0]=='9':</strong><br style="line-height: normal;" />
...      <strong style="line-height: normal;">print "Running 9i"</strong><br style="line-height: normal;" />
...<br style="line-height: normal;" />
Running 10g<br style="line-height: normal;" />
>>> <strong style="line-height: normal;">print db.dsn</strong><br style="line-height: normal;" />
localhost:1521/XE
第二步:建立Cursor光标
>>>cursor = db.cursor() 建立一个cursor
之后,我们可以调用这个cursor.execute(‘SQL‘) 来执行SQL语句。比如:
>>>cursor.execute(‘select * from tabs’)
执行完毕以后,可以调用cursor.fetchall()一次取完所有结果,或者cursor.fetchone()一次取一行结果
>>>row=cursor.fetchall()
>>>for x in row:
      For y in x:
         Print y,
       Print
这样就可以按照表格的形式打印取得的结果了!
在从oracle取出数据的时候,考虑到它的数据类型了吗?下面就是数据类型的对应表

Datatypes

During the fetch stage, basic Oracle data types get mapped into their Python equivalents. cx_Oracle maintains a separate set of data types that helps in this transition. The Oracle - cx_Oracle - Python mappings are:
Oracle
cx_Oracle
Python
VARCHAR2
NVARCHAR2
LONG
cx_Oracle.STRING
str
CHAR
cx_Oracle.FIXED_CHAR
NUMBER
cx_Oracle.NUMBER
int
FLOAT
float
DATE
cx_Oracle.DATETIME
datetime.datetime
TIMESTAMP
cx_Oracle.TIMESTAMP
CLOB
cx_Oracle.CLOB
cx_Oracle.LOB
BLOB
cx_Oracle.BLOB
带参数的查询:
>>> named_params = {'dept_id':50, 'sal':1000}
>>> query1 = cursor.execute('SELECT * FROM employees 
WHERE department_id=:dept_id AND salary>:sal', named_params)
>>> query2 = cursor.execute('SELECT * FROM employees 
WHERE department_id=:dept_id AND salary>:sal', dept_id=50, sal=1000)
这种是名字参数,还可以按位置参数:
r1 = cursor.execute('SELECT * FROM locations 
WHERE country_id=:1 AND city=:2', ('US', 'Seattle'))
注意:
当只有一次参数的时候,也要把它写成元组的形式,比如
Cursor.execute(‘select name from user where id=:1’,(login_Id,))
千万要注意,login_id后面还带有一个逗号,如果没有逗号,他其实就是一个数据对象,但是当他后面有个逗号的时候,他就变成了元组的一个数据项,千万要记住啊,我就是在这里徘徊了很久。!
Cursor. Prepare的用法,
这个方法就是在prepare之后,你再去execute的时候,就不用写上sql语句参数了
>>> cursor.prepare('SELECT * FROM jobs WHERE min_salary>:min')
>>> r = cursor.execute(None, {'min':1000}) #注意,第一个参数是None,
一次执行多条sql语句
Large insert operations don't require many separate inserts because Python fully supports inserting many rows at once with the cx_Oracle.Cursor.executemany method. Limiting the number of execute operations improves program performance a lot and should be the first thing to think about when writing applications heavy on INSERTs.
Let's create a table for a Python module list, this time directly from Python. You will drop it later.
>>> create_table = """<br style="line-height: normal;" />
CREATE TABLE python_modules (<br style="line-height: normal;" />
  module_name VARCHAR2(50) NOT NULL,<br style="line-height: normal;" />
  file_path VARCHAR2(300) NOT NULL<br style="line-height: normal;" />
)<br style="line-height: normal;" />
"""<br style="line-height: normal;" />
>>> from sys import modules<br style="line-height: normal;" />
>>> cursor.execute(create_table)<br style="line-height: normal;" />
>>> M = []<br style="line-height: normal;" />
>>> for m_name, m_info in modules.items():<br style="line-height: normal;" />
...     try:<br style="line-height: normal;" />
...       M.append((m_name, m_info.__file__))<br style="line-height: normal;" />
...     except AttributeError:<br style="line-height: normal;" />
...       pass<br style="line-height: normal;" />
...<br style="line-height: normal;" />
>>> len(M)<br style="line-height: normal;" />
76<br style="line-height: normal;" />
>>> cursor.prepare("INSERT INTO python_modules(module_name, file_path) VALUES (:1, :2)")<br style="line-height: normal;" />
>>> cursor.executemany(None, M)<br style="line-height: normal;" />
>>> db.commit()<br style="line-height: normal;" />
>>> r = cursor.execute("SELECT COUNT(*) FROM python_modules")<br style="line-height: normal;" />
>>> print cursor.fetchone()<br style="line-height: normal;" />
(76,)<br style="line-height: normal;" />
>>> cursor.execute("DROP TABLE python_modules PURGE")
您可以通过以下步骤下载和安装cx_Oracle库: 1. 首先,您可以从https://pypi.org/project/cx-Oracle/5.3/#files下载cx_Oracle的适用版本。请确保选择与您的Python版本和操作系统相匹配的文件。比如,如果您使用的是Python 3.6和64位的Windows系统,您可以下载cx_Oracle-5.3-11g.win-amd64-py3.6-2.exe文件。 2. 下载完成后,双击运行下载的安装文件,按照提示进行安装。在安装过程中,您可能需要指定要使用的Python环境。如果您的系统中安装了多个Python版本,请确保选择正确的版本。如果安装后出现问题,可能需要修改您的Python系统PATH。 3. 另外,您还需要安装Oracle客户端。您可以登录https://pypi.org/project/cx-Oracle/#files,下载与您的Python版本和操作系统相匹配的whl文件。比如,如果您使用的是Python 3.6和64位的Windows系统,您可以下载cx_Oracle-8.3.0-cp36-cp36m-win_amd64.whl文件。 4. 下载完成后,将whl文件放置在您希望安装的位置,比如d:\python。 5. 打开命令行窗口,进入到whl文件所在的目录,然后运行以下命令来安装cx_Oracle: ``` pip install cx_Oracle-8.3.0-cp36-cp36m-win_amd64.whl ``` 6. 安装完成后,您可以在Python代码中导入cx_Oracle库,并使用它来连接和操作Oracle数据库。以下是一个连接测试的示例代码: ```python import pandas as pd import cx_Oracle as oracle db = oracle.connect('用户名/密码@主机ip地址/orcl') cursor = db.cursor() sql = 'select * from dual' df = pd.read_sql(sql, con=db) cursor.close() db.close() df.head() ``` 请注意,您需要将用户名、密码和主机IP地址替换为实际的值。这段代码将连接到Oracle数据库,并从dual表中读取数据,并使用pandas库将结果存储在DataFrame中。 #### 引用[.reference_title] - *1* *3* [python中安装cx_Oracle模块](https://blog.csdn.net/weixin_44100044/article/details/126034475)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] - *2* [windows 下Python或者Spyder离线安装cx_Oracle 包](https://blog.csdn.net/u013756405/article/details/125766396)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v91^control_2,239^v3^insert_chatgpt"}} ] [.reference_item] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值