background :
1、 It is necessary to use python Connect the database to verify the data calculated on the interface
2、 Usually used to query the database PLSQL, Used by the company orcal database
3、cmd Open Command Prompt , Input python
, Prompt version bit 3.9,64 position ,plsql newly build sql window Inquire about , Input select * from v$version
, notice plsql yes 64 Bit
4、 Write it at the front : Installed python、instantclient The number of digits should be consistent
5、python Connect orcal The database needs to use cx_Oracle
This library ,python3 The above version uses the command on the terminal pip3 install cx_Oracle
install , If the installation fails, you can see how I solved it in my last article
6、 See the figure below to show that the installation is successful
7、 Show installation success , But when writing code, the import always reports an error ?
terms of settlement : Let's see if there is... Under the left , If not, restart pycharm have a look , If not , double-click shift key , open , Search manually and add ( That's how I solved it )
8、 Then we start writing code , The connection code is as follows :
import cx_Oracle
# Connect to database , There are several ways of writing , Subsequent complement
conn = cx_Oracle.connect(' user name ', ' password ', ' Address : port / service ') # Just replace it with the corresponding value
# Use cursor() Method get operation cursor
cursor = conn.cursor()
# Use execute Method execution SQL sentence
result = cursor.execute("sql sentence ")
# Multiple lines sql You can use three quotation marks to wrap lines , It looks beautiful
# Use fetchone() Method to get a piece of data
data = result.fetchone()
# Get all the data
all_data = result.fetchall()
# Get some data ,8 strip
many_data = result.fetchmany(8)
print(data)
cursor.close()
conn.close()
The demerit recorded in the query contains Chinese characters that are garbled , write in
import os
os.environ['NLS_LANG'] = 'SIMPLIFIED CHINESE_CHINA.ZHS16GBK'
9、 After writing, you can run the program , The following error is reported ( There are many online solutions , We really need to judge our own situation before making changes )
The possible reasons are :
10.1 Change the environment variable first , There are three things that need to be changed **( This is an important step , Can not correct mistakes )**:
Create the following figure in the system variable , write in instantclient Storage path , The address should be copied completely , To the folder address at the end of the innermost number
Path In the path , Add the above path
New system variable , Fill in the following values
10.2 hold instant client The following under the folder 4 Copy and paste a file into python Installation directory -Lib -site-packages Under the folder , It should be three of them , I can't tell which one succeeded after I tried , It was copied together
10.3 Restart pycharm, Just run the code