Python使用cx_Oracle模块连接Oracle数据库及查询示例
本文介绍Python中使用cx_Oracle模块连接Oracle数据库的常见错误及解决方法。通过对比未设置NLS_LANG环境变量导致的TNS连接超时错误,与正确配置后的成功查询示例,展示如何编写连接代码、执行SQL语句并获取结果,帮助开发者快速排查连接问题。
Python cx_Oracle连接与查询示例
本文介绍Python中使用cx_Oracle模块进行数据库查询操作的具体实现方法,供读者参考学习。
未配置环境变量的连接尝试
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
from pprint import pprint
import csv
import time
import re
import binascii
print time.ctime()
try:
conn = cx_Oracle.connect('tlcbuser/tlcbuser@10.5.100.232/tlyy')
# cursor = conn.cursor()
# xsql="select * from tlcb_mon_device a where a.ipaddr='10.3.244.1'"
# r = cursor.execute(xsql)
# print r
except Exception,e:
print e
print type(e)
print str(e).decode('UTF-8').encode('GBK')
print time.ctime()
运行脚本后出现以下错误信息: C:\Python27\python.exe C:/Users/tlcb/PycharmProjects/untitled/a6.py Mon Oct 22 10:35:59 2018 ORA-12170: TNS: 连接超时 <class 'cx_Oracle.DatabaseError'> Mon Oct 22 10:36:20 2018 Process finished with exit code 0
添加NLS_LANG配置后的连接测试
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
from pprint import pprint
import csv
import time
import re
import binascii
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
print time.ctime()
try:
conn = cx_Oracle.connect('tlcbuser/tlcbuser@10.5.100.232/tlyy')
# cursor = conn.cursor()
# xsql="select * from tlcb_mon_device a where a.ipaddr='10.3.244.1'"
# r = cursor.execute(xsql)
# print r
except Exception,e:
print e
print type(e)
print time.ctime()
再次尝试运行脚本,依旧报出相同错误: C:\Python27\python.exe C:/Users/tlcb/PycharmProjects/untitled/a6.py Mon Oct 22 10:44:20 2018 ORA-12170: TNS: 连接超时 <class 'cx_Oracle.DatabaseError'> Mon Oct 22 10:44:41 2018 Process finished with exit code 0
成功执行查询并获取结果
# !/usr/bin/env python
# -*- coding: utf-8 -*-
import cx_Oracle
from pprint import pprint
import csv
import time
import re
import binascii
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
print time.ctime()
conn = cx_Oracle.connect('test/test@10.10.17.200/serv')
cursor = conn.cursor()
xsql="select 'aaa' from dual"
cursor.execute(xsql)
result = cursor.fetchall()
print result
在修正配置后重新运行脚本,成功获取查询结果: C:\Python27\python.exe C:/Users/tlcb/PycharmProjects/untitled/rizhiyi/a7.py Mon Oct 22 11:33:52 2018 [('aaa',)] Process finished with exit code 0
更多关于Python相关内容感兴趣的读者可查看本站专题:《Python常见数据库操作技巧汇总》、《Python编码操作技巧总结》、《Python数据结构与算法教程》、《Python Socket编程技巧总结》、《Python函数使用技巧总结》、《Python字符串操作技巧汇总》、《Python入门与进阶经典教程》及《Python文件与目录操作技巧汇总》
希望本文所述对大家Python程序设计有所帮助。
本站声明
本文内容仅供参考,不代表本站观点。转载或引用请注明出处。如发现内容问题,请通过联系我们页面反馈。













