search
HomeBackend DevelopmentPython TutorialSimple methods and encapsulated class examples for operating Oracle database in Python

This article mainly introduces the simple methods and encapsulation classes of Python to operate the Oracle database. It analyzes the basic operations of Python's simple connection, query, and closing of the Oracle database in the form of examples, and provides a Python encapsulation for various Oracle operations. Class, friends who need it can refer to

The examples in this article describe simple methods and encapsulation classes for operating Oracle databases in Python. I would like to share it with you for your reference. The details are as follows:

I recently came into contact with Oracle at work and found that it would be much more convenient to use Python scripts in many places, so I wanted to learn the basic method of operating Oracle in Python first. .

Considering the use of Oracle and the existence of NetConfig of OracleClient, I think connecting it should not be a simple matter.

Sure enough, I searched for several connection methods on the Internet, and then I drew it for a long time, but I couldn't find a scoop.

Method 1: Username, password and monitoring are used as parameters respectively

conn=cx_Oracle.connect('用户名','密码','数据库地址:数据库端口/SID')

According to several articles I read As a reminder that I made an error in writing the code, I found that the configuration item for python to connect to the database should be related to the configuration file tnsnames.ora of the Oracle client. But my configuration items did not have a SID item, and I didn’t know what SID was at first. I just followed what was written on the Internet, so this method failed. Later, I figured out that I need to add a SID to the configuration item, and then I thought about whether my system would need to be restarted after this thing is configured. So, let’s look at other methods first….

Method 2: Username, password and listener are used as one parameter

conn=cx_Oracle.connect('用户名/密码@数据库地址:数据库端口/SID')

This method is basically the same as method one, changing the soup without changing the medicine...

Method 3: Use tns configuration information

conn=cx_Oracle.connect('用户名','密码',tns)

The code on the Internet uses a function to obtain tns, and it still uses SID, but... the configuration items that I can already use do not have SID, so I use

tns=cx_Oracle.makedsn('数据库地址','数据库端口', 'SID')

Still doesn’t work, but look at the generation method of this tns which is similar to the two methods above. But I found that the data generated after I randomly input a SID is like this.

(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SID=XE)))

However, the configuration items of my client are probably like this,

(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)( PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=KGDB)))

I guess they look the same and the types are all string types. Try putting them directly in my file. Try assigning the configuration items to tns.

tns = '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=KGDB)))'
conn = cx_Oracle.connect('nicker', '123456', tns)

Hmm. Success~

Finally, post a complete code of the basic usage

#coding:utf-8
import cx_Oracle
# 创建数据库连接
# cx_Oracle.connect('username','pwd','ora的tns信息')
# oracle数据库的tns信息,从tnsnames.ora中找到plsql可用的配置项,将该配置项直接拷贝过来即可
ora_tns = '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=127.0.0.1)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=KGDB)))'
conn = cx_Oracle.connect('nicker', '123456', ora_tns)
# 操作游标
cursor = conn.cursor()
# 执行查询
cursor.execute("SELECT * FROM inst_info")
# 获取返回信息
rs = cursor.fetchall()
# 输出信息
for v in rs:
  print v
#关闭连接,释放资源
cursor.close()
conn.close()

Observation and discovery summary is very important, understand You also need to

paste a class that encapsulates Oracle

#coding:utf-8
import cx_Oracle
# 封装的类
class cxOracle:
  '''
  tns的取值tnsnames.ora对应的配置项的值,如:
  tns = '(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.16.18.23)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=MYDB)))'
  '''
  def __init__(self ,uname, upwd,tns ):
    self ._uname = uname
    self ._upwd = upwd
    self ._tns = tns
    self ._conn = None
    self ._ReConnect()
  def _ReConnect(self ):
    if not self._conn :
      self ._conn = cx_Oracle.connect (self. _uname, self ._upwd, self._tns)
    else:
      pass
  def __del__(self ):
    if self. _conn:
      self ._conn. close()
      self ._conn = None
  def _NewCursor(self ):
    cur = self. _conn.cursor ()
    if cur:
      return cur
    else:
      print "#Error# Get New Cursor Failed."
      return None
  def _DelCursor(self , cur):
    if cur:
      cur .close()
  # 检查是否允许执行的sql语句
  def _PermitedUpdateSql(self ,sql):
    rt = True
    lrsql = sql. lower()
    sql_elems = [ lrsql.strip ().split()]
    # update和delete最少有四个单词项
    if len( sql_elems) < 4 :
      rt = False
    # 更新删除语句,判断首单词,不带where语句的sql不予执行
    elif sql_elems[0] in [ &#39;update&#39;, &#39;delete&#39;]:
      if &#39;where&#39; not in sql_elems :
        rt = False
    return rt
  # 导出结果为文件
  def Export(self , sql, file_name, colfg =&#39;||&#39;):
    rt = self. Query(sql )
    if rt:
      with open( file_name, &#39;a&#39;) as fd:
        for row in rt:
          ln_info = &#39;&#39;
          for col in row:
             ln_info += str( col) + colfg
          ln_info += &#39;\n&#39;
          fd .write( ln_info)
  # 查询
  def Query(self , sql, nStart=0 , nNum=- 1):
    rt = []
    # 获取cursor
    cur = self. _NewCursor()
    if not cur:
      return rt
    # 查询到列表
    cur .execute(sql)
    if ( nStart==0 ) and (nNum==1 ):
      rt .append( cur.fetchone ())
    else:
      rs = cur. fetchall()
      if nNum==- 1:
        rt .extend( rs[nStart:])
      else:
        rt .extend( rs[nStart:nStart +nNum])
    # 释放cursor
    self ._DelCursor(cur)
    return rt
  # 更新
  def Exec(self ,sql):
    # 获取cursor
    rt = None
    cur = self. _NewCursor()
    if not cur:
      return rt
    # 判断sql是否允许其执行
    if not _PermitedUpdateSql(sql ):
      return rt
    # 执行语句
    rt = cur. execute(sql )
    # 释放cursor
    self ._DelCursor(cur)
    return rt
# 类使用示例
tns = &#39;(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=10.16.17.46)(PORT=1521)))(CONNECT_DATA=(SERVICE_NAME=MYDB)))&#39;
ora = cxOracle (&#39;nicker&#39;, &#39;123456&#39;, tns)
# 导出结果为文件
rs = ora .Export("SELECT * FROM org", &#39;1.txt&#39;)
# 查询结果到列表
rs = ora.Query("SELECT * FROM org")
print rs
# 更新数据
ora.Exec("update org set org_name=&#39;NewNameForUpdate&#39; where org_id=123456;")

Related recommendations:

Detailed explanation of Python using cx_Oracle module to operate Oracle database

The above is the detailed content of Simple methods and encapsulated class examples for operating Oracle database in Python. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

How are arrays used in image processing with Python?How are arrays used in image processing with Python?May 07, 2025 am 12:04 AM

ArraysarecrucialinPythonimageprocessingastheyenableefficientmanipulationandanalysisofimagedata.1)ImagesareconvertedtoNumPyarrays,withgrayscaleimagesas2Darraysandcolorimagesas3Darrays.2)Arraysallowforvectorizedoperations,enablingfastadjustmentslikebri

For what types of operations are arrays significantly faster than lists?For what types of operations are arrays significantly faster than lists?May 07, 2025 am 12:01 AM

Arraysaresignificantlyfasterthanlistsforoperationsbenefitingfromdirectmemoryaccessandfixed-sizestructures.1)Accessingelements:Arraysprovideconstant-timeaccessduetocontiguousmemorystorage.2)Iteration:Arraysleveragecachelocalityforfasteriteration.3)Mem

Explain the performance differences in element-wise operations between lists and arrays.Explain the performance differences in element-wise operations between lists and arrays.May 06, 2025 am 12:15 AM

Arraysarebetterforelement-wiseoperationsduetofasteraccessandoptimizedimplementations.1)Arrayshavecontiguousmemoryfordirectaccess,enhancingperformance.2)Listsareflexiblebutslowerduetopotentialdynamicresizing.3)Forlargedatasets,arrays,especiallywithlib

How can you perform mathematical operations on entire NumPy arrays efficiently?How can you perform mathematical operations on entire NumPy arrays efficiently?May 06, 2025 am 12:15 AM

Mathematical operations of the entire array in NumPy can be efficiently implemented through vectorized operations. 1) Use simple operators such as addition (arr 2) to perform operations on arrays. 2) NumPy uses the underlying C language library, which improves the computing speed. 3) You can perform complex operations such as multiplication, division, and exponents. 4) Pay attention to broadcast operations to ensure that the array shape is compatible. 5) Using NumPy functions such as np.sum() can significantly improve performance.

How do you insert elements into a Python array?How do you insert elements into a Python array?May 06, 2025 am 12:14 AM

In Python, there are two main methods for inserting elements into a list: 1) Using the insert(index, value) method, you can insert elements at the specified index, but inserting at the beginning of a large list is inefficient; 2) Using the append(value) method, add elements at the end of the list, which is highly efficient. For large lists, it is recommended to use append() or consider using deque or NumPy arrays to optimize performance.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

Safe Exam Browser

Safe Exam Browser

Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software