[Python] Python connects to Oracle database

Preface

Recently, I was writing a project in Python, and I needed to use a database to record user information. It happened that my native language was Oracle, so I studied how Python connects to the Oracle database. Record a ha, in case you need it next time, please correct me.

surroundings

The project is the library used in the
Python version of the virtual integrated environment built with MiniConda

Insert picture description here


  • cx_Oracle

Oracle version

Insert picture description here

step

The first step: install cx_Oracle

command

pip install cx_Oracle
Insert picture description here


Prompt that Successfully installed cx-Oracle-8.2.0 is installed successfully

Step 2: Connect to the database

Use cx_Oracle.connect to establish a connection, the parameter format is
username/[email protected]:port number/SERVICE_NAME

conn = cx_Oracle.connect('SCOTT/[email protected]:1521/XE')

Step 3: Operate the cursor

  1. Use cursor() method to get operation cursor
cursor = conn.cursor()
  1. Use the execute method to execute SQL statements
result = cursor.execute('SELECT * FROM V$VERSION')
  1. retrieve data
fetchone()方法获取一条数据
data=cursor.fetchone()

fetchall()方法获取所有数据
all_data = cursor.fetchall()

fetchmany()方法获取部分数据,8条
many_data=cursor.fetchmany(8)
  1. Close cursor
cursor.close()

Insert picture description here