python连接centos上的oracle数据库 附完整代码

下载cx_Oracle模块

yum -y install python3-pip #Centos 7
dnf install python3-pip #CentOS 8
pip2 install cx_Oracle

安装PIP
安装插件

测试连接

连接对象

su - oracle
python3
#!/usr/bin/python
#coding=utf-8
import cx_Oracle
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
conn1 = cx_Oracle.connect('user','pass','127.0.0.1:1521/instance')
conn2 = cx_Oracle.connect('user/pass@localhost:1521/instance')
conn3 = cx_Oracle.connect('user','pass','localhost:1521/instance')
cursor= conn1.cursor()
hrm_params = {'login_id':'01040004', 'last_name':'马学生'}
query1 = cursor.execute('SELECT * FROM HrmResource WHERE loginid=:login_id and lastname=:last_name', hrm_params)
query2 = cursor.execute('SELECT * FROM HrmResource WHERE loginid=:login_id and lastname=:last_name', login_id='01040004', last_name='马学生')
print(cursor.bindnames())
print(query1.fetchone())
datetime=cursor.execute('select sysdate from dual')
datetime.fetchone()
cursor.close()
conn.close()
conn1.close()

cursor对象详解

  • cx_Oracle.Cursor.execute(statement,[parameters], **keyword_parameters) #接收单个参数SQL,直接操作数据库,也可以通过绑定变量执行动态SQL,parames或keyworparameters可以是字典、序列或一组关键字参数。
  • cx_Oracle.Cursor.executemany(statement,parameters) #特别有用的批量插入,避免一次只能插入一条;
  • Fetch(optional)#仅用于查询,因为DDL和DCL语句没有返回结果。如果cursor没有执行查询,会抛出InterfaceError异常。
  • cx_Oracle.Cursor.fetchall()#获取所有结果集,返回元祖列表,如果没有有效行,返回空列表。
  • cx_Oracle.Cursor.fetchmany([rows_no])#从数据库中取下一个rows_no数据
  • cx_Oracle.Cursor.fetchone()#从数据库中取单个元祖,如果没有有效数据返回none

完整代码

import cx_Oracle
import os
from sys import modules

# 连接Oracle数据库
class oracleOperation():
	def openOracleConn(self):
		os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
		highway = cx_Oracle.connect('user', 'pass', '127.0.0.1:1521/instance')
		# cx_Oracle.connect("%s/%s@%s/%s" % (userName,password,host,instance))
		return highway

	def select(self, connection):
		cursor = connection.cursor()
		# 数据库操作
		# 1.查询 不用提供参数
		sql = 'SELECT id,loginid,password,lastname,pinyinlastname FROM HrmResource where id < 790'
		result = cursor.execute(sql)
		print('type of result', type(result))  # 获取使用cursor对象的execute的方法返回的对象的类型
		print('result:', result)  # 获取使用cursor对象的execute的方法返回的对象
		print("Number of rows returned: %d" % cursor.rowcount)
		rows = cursor.fetchall()  # 得到所有数据集
		print("rows:", rows)  # fetchall()方法得到的到底是设么类型的对象
		for i in rows:
			print('ID:', i[0])
			print('loginid:', i[1])
			print('password:', i[2])
		cursor.close()

	# 2 条件查询 需提供参数
	def factorSelect(self, connection, param):
		cursor = connection.cursor()
		# 带参数的查询  ,例子如下:
		# query1 = cursor.execute('SELECT * FROM employees  WHERE  department_id =:dept_id AND salary >:sal', named_params)
		sql = 'SELECT id,loginid,password,lastname,pinyinlastname FROM HrmResource where  id<:p_id'
		query1 = cursor.execute(sql, param)  # 特别的注意,具体 的条件查询的格式
		row = cursor.fetchall()
		print(row)
		cursor.close()
		connection.close()
	pass

	# 3 插入1 不用提供参数
	def insert(self, connection):
		cursor = connection.cursor()
		sql = "insert into Python_Oracle (id,kinds,numbers) values (:id,:kinds,:numbers)"
		cursor.prepare(sql)
		# 2,'西瓜','100kg'
		xx = [{'id': 6}, {'kinds': '荔枝'}, {'numbers': '100kg'}]
		# result=cursor.execute(None,{'id':6,'kinds':'荔枝','numbers':'100kg'})
		# result=cursor.execute(None,xx)
		result = cursor.execute(None, xx)
		print("Insert result:", result)
		connection.commit()
		cursor.close()
		connection.close()
	pass

	# 4插入2 需提供参数
	def insert2(self, connection, insertParam=[]):
		cursor = connection.cursor()
		# M=[(11,'sa','sa'),]
		sql = "insert into Python_Oracle (id,kinds,numbers) values (:id,:kinds,:numbers)"
		if (len(insertParam) == 0):
			print("插入的数据行的参数不能为空!")
		else:
			cursor.prepare(sql)
			result = cursor.executemany(None, insertParam)
			print("Insert result:", result)
			# count=cursor.execute("SELECT COUNT(*) FROM python_modules")
			# print("count of python_modules:",count)
		connection.commit()
		cursor.close()
		connection.close()
	pass

	# 插入3
	def insert3(self, connection):
		cursor = connection.cursor()
		create_table = """
		CREATE TABLE python_modules1 (
		module_name VARCHAR2(50) NOT NULL,
		file_path VARCHAR2(300) NOT NULL
		)
		"""
		# cursor.execute(create_table)

		M = []
		for m_name, m_info in modules.items():
			try:
				if (m_info.__file__ == None):
					m_info.__file__ = 'None'
				M.append((m_name, m_info.__file__))
			except AttributeError:
				pass
		print("M", M)
		for item in M:
			print(item)

		sql = "INSERT INTO python_modules1(module_name, file_path) VALUES (:1, :2)"
		cursor.prepare(sql)
		cursor.executemany(None, M)
		connection.commit()
		count = cursor.execute("SELECT COUNT(*) FROM python_modules1")
		print("count of python_modules1:", count)
		connection.commit()
		cursor.close()
		connection.close()
	pass

	def Delete(self, conn):
		cursor = conn.cursor()
		sql = "delete "
	pass

if __name__ == '__main__':
	db = oracleOperation()
	connection = db.openOracleConn()

	# 能运行的无条件查询语句
	# db.select(connection)

	# 能够运行的条件查询语句
	hrm_params = {'p_id': 790}
	# db.factorSelect(connection,hrm_params)

	db.insert3(connection)

	# 自己的能够运行的insert语句
	# insertParam=[(5,'大象','1T'),(6,'蚂蚁','0.001g')]
	# db.insert2(connection,insertParam)

相关问题解决

oracle乱码问题解决方案

# -*- coding: utf-8 -*-
import cx_Oracle
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.UTF8'
conn1 = cx_Oracle.connect('用户','密码','地址:端口/instance')
cursor= conn1.cursor()
hrm_params = {'login_id':'01040004', 'last_name':'马学生'}
query1 = cursor.execute('SELECT * FROM HrmResource WHERE loginid=:login_id and lastname=:last_name', hrm_params)
print(cursor.bindnames())
print(query1.fetchone())
#print(query1.fetchone().decode('utf-8'))
#cursor.execute('insert into test_ccc values(1,sysdate,\'北\')') 
#conn1.commit() 
conn1.close()

解决DatabaseError: DPI-1047

错误截图
Oracle Instant Client Downloads 需要安装oracle的即时客户端
oracle instant
19.5
解压 instantclient-basic-windows.x64-19.5.0.0.0dbru.zip到目录中,添加这个目录到环境变量path中。【高级系统设置】
环境变量

参考链接

Error: DPI-1047: Cannot locate a 64-bit Oracle Client library:"
python操作oracle完整教程

发布了37 篇原创文章 · 获赞 9 · 访问量 2万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章