Python使用Oracle数据库详解与flask_sqlalchemy连接多个数据库
一、安装cx_Oraclepip3 install cx_Oracle二、连接数据库1、cx_Oracle连接方法dsnStr = cx_Oracle.makedsn('ip', port, service_name='orcl')conn = cx_Oracle.connect('username', 'password', dsn = dsnStr)cur = conn.cursor()dat
一、安装cx_Oracle
pip3 install cx_Oracle
二、连接数据库
1、cx_Oracle连接方法
dsnStr = cx_Oracle.makedsn('ip', port, service_name='orcl')
conn = cx_Oracle.connect('username', 'password', dsn = dsnStr)
cur = conn.cursor()
datas =cur.execute("select * from person where id = '3'").fetchall()
for item in datas:
print(item)
2、SQLAlchemy 连接方式(flask_sqlalchemy连接多个数据库)
from flask_sqlalchemy import SQLAlchemy
from flask import Flask
from datetime import datetime
import cx_Oracle
app = Flask(__name__)
dsnStr = cx_Oracle.makedsn('ip', 1521, service_name='orcl')
connect_str = "oracle://%s:%s@%s" %('usename', ' password', dsnStr)
# 配置多个数据库连接
SQLALCHEMY_BINDS = {
'db1': 'mysql+pymysql://root:password@ip:3306/test?charset=utf8',
'db2': 'oracle://username:password@ip:1521/orcl' #
# "db3": connect_str #oracle 连接方式二
}
app.config['SQLALCHEMY_DATABASE_URI'] = "" # 默认数据库引擎
app.config['SQLALCHEMY_BINDS'] = SQLALCHEMY_BINDS
app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False
# app.config['SQLALCHEMY_ECHO'] = True
db = SQLAlchemy(app)
engine = db.get_engine(bind="db2")
datas = engine.execute(f"select * from user where ID = '{'1'}'")
source = [dict(i) for i in datas]
print(source)
场景:python3 使用cx_Oracle进行Oracle数据库操作
报错具体信息:cx_Oracle.DatabaseError: DPI-1047: Cannot locate a 64-bit Oracle Client library: “dlopen(libclntsh.dylib, 1): image not found”. See https://cx-oracle.readthedocs.io/en/latest/user_guide/installation.html for help
首先下载instantclient:Oracle Instant Client Downloads
下载后解压 ,在用户目录下创建lib文件夹
mkdir lib
创建软链接到lib目录下
ln -s /instantclient解压的目录/libclntsh.dylib ~/lib/
运行报错无法验证开发者,找到无法打开的文件右键在打开方式里找到pycharm打开(任意文件格式)再次运行就可以了
更多推荐
所有评论(0)