Home Backend Development Python Tutorial Simple methods and encapsulated class examples for operating Oracle database in Python

Simple methods and encapsulated class examples for operating Oracle database in Python

May 07, 2018 pm 02:25 PM
oracle python database

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

1

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

Copy after login

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

1

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

Copy after login

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

Method 3: Use tns configuration information

1

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

Copy after login

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

1

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

Copy after login

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.

1

2

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)

Copy after login

Hmm. Success~

Finally, post a complete code of the basic usage

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#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()

Copy after login

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

paste a class that encapsulates Oracle

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

27

28

29

30

31

32

33

34

35

36

37

38

39

40

41

42

43

44

45

46

47

48

49

50

51

52

53

54

55

56

57

58

59

60

61

62

63

64

65

66

67

68

69

70

71

72

73

74

75

76

77

78

79

80

81

82

83

84

85

86

87

88

89

90

91

92

93

94

95

96

97

98

99

100

101

102

#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;")

Copy after login

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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1653
14
PHP Tutorial
1251
29
C# Tutorial
1224
24
PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Python vs. JavaScript: The Learning Curve and Ease of Use Python vs. JavaScript: The Learning Curve and Ease of Use Apr 16, 2025 am 12:12 AM

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

How to run sublime code python How to run sublime code python Apr 16, 2025 am 08:48 AM

To run Python code in Sublime Text, you need to install the Python plug-in first, then create a .py file and write the code, and finally press Ctrl B to run the code, and the output will be displayed in the console.

How to run python with notepad How to run python with notepad Apr 16, 2025 pm 07:33 PM

Running Python code in Notepad requires the Python executable and NppExec plug-in to be installed. After installing Python and adding PATH to it, configure the command "python" and the parameter "{CURRENT_DIRECTORY}{FILE_NAME}" in the NppExec plug-in to run Python code in Notepad through the shortcut key "F6".

Oracle's Role in the Business World Oracle's Role in the Business World Apr 23, 2025 am 12:01 AM

Oracle is not only a database company, but also a leader in cloud computing and ERP systems. 1. Oracle provides comprehensive solutions from database to cloud services and ERP systems. 2. OracleCloud challenges AWS and Azure, providing IaaS, PaaS and SaaS services. 3. Oracle's ERP systems such as E-BusinessSuite and FusionApplications help enterprises optimize operations.

Golang vs. Python: Key Differences and Similarities Golang vs. Python: Key Differences and Similarities Apr 17, 2025 am 12:15 AM

Golang and Python each have their own advantages: Golang is suitable for high performance and concurrent programming, while Python is suitable for data science and web development. Golang is known for its concurrency model and efficient performance, while Python is known for its concise syntax and rich library ecosystem.

See all articles