python3向oracle插入数据

python3.7连接oracle

本文示例使用 oracle-11.2.0.4.0版本

oracle-client准备部分

1.下载oracle client,下载地址

注意:

1.保证与oracle服务器版本统一

2.python3 ,oracle服务器,oracle client统一使用64位或者32位

2.先解压缩instantclient-basic-linux.x64-11.2.0.4.0.zip,后解压缩instantclient-sdk-linux.x64-11.2.0.4.0.zip

3.进入目录instantclient_11_2,创建软链接

ln -s libclntsh.so.11.1  libclntsh.so

4.在刚刚解压得到的instantclient_11_2文件夹下新建network/admin

5.在刚刚创建的目录下创建network/admin创建文件tnsnames.ora,模板如下(SERVICE_NAME请填写服务器SID)

ORCL =
 (DESCRIPTION =
   (ADDRESS = (PROTOCOL = TCP)(HOST = 127.0.0.1)(PORT = 1521))
   (CONNECT_DATA =
     (SERVER = DEDICATED)
     (SERVICE_NAME = orcl)
   )
 )

6.修改环境变量(自行更改oracle client解压的路径)

vim /etc/profile

export ORACLE_HOME=/usr/local/instantclient_11_2
export LD_LIBRARY_PATH=$ORACLE_HOME:$LD_LIBRARY_PATH
export NLS_LANG=AMERICAN_AMERICA.AL32UTF8
export TNS_ADMIN=$ORACLE_HOME/network/admin
export PATH=$ORACLE_HOME:$PATH

source /etc/profile

 

python准备部分

通过pip 下载库cx-Oracle

pip install cx-Oracle

插入数据

#coding=utf-8
#!/usr/bin/python3
import pymysql
import threading
import time
import cx_Oracle
‘‘‘
前提:在oracle中设置主键字段自增
‘‘‘
def try_to_connect_and_insert():
        username="test1"
        userpwd="123"
        host="127.0.0.1"
        port=1521
        dbname="orcl"
        insertCount = 0
        dsn=cx_Oracle.makedsn(host,port,dbname)
        try:
                connection=cx_Oracle.connect(username,userpwd,dsn)
                connection.autocommit=True
                sql="insert into TST01(NAME,PRICE,MDATE) VALUES(‘TEST‘,1.0001,to_date(‘20200121‘,‘yyyymmdd‘))"
                cursor=connection.cursor()
                for i in range(500000-insertCount):
                        insertCount=i
                        cursor.execute(sql)
                print(insertCount)
                cursor.close()
                connection.close()
        except Exception as e:
                print(e)
                print(insertCount)


if __name__ == __main__:
        for i in range (10):
                T = threading.Thread(target=try_to_connect_and_insert)
                T.start()
                time.sleep(1)

 

运行python脚本,完

 

以下为本人在运行时遇到的问题

=======================================

1.  DPI-1047: 64-bit Oracle Client library cannot be loaded: "libclntsh.so

当我的python版本,oracle版本,Oracle Instant Client版本都一致的情况下,依然报这个错误。需要执行以下命令

sh -c "echo /usr/local/instantclient_11_2 > /etc/ld.so.conf.d/oracle-instantclient.conf"
ldconfig

 

python3向oracle插入数据

上一篇:创建数据库


下一篇:连接远程服务器MYSQL数据库总结