使用SQLALCHEMY连接到Oracle数据库

时间:2015-02-11 11:44:26

标签: sqlalchemy

我能够成功连接到sqlite数据库并使用以下命令集访问特定表。

from sqlalchemy import create_engine, MetaData, Table, and_

from sqlalchemy.sql import select

from pandas import DataFrame 

db = create_engine('sqlite:///path\\database.db')

metadata = MetaData(db)

table = Table('table name', metadata, autoload=True)

我可以使用cx_Oracle库从oracle数据库中获取数据。

但是,当我尝试连接到sqlalchemy中的Oracle数据库时,我收到以下错误

NoSuchTableError: <table name>

我使用了以下命令:

db = create_engine('oracle://username:password@hostname:1521/instance name',echo='debug')

md = MetaData(bind=db)

t = Table('table name', md, autoload=True,schema='schema name')

当我使用以下命令时

t= Table('table name', md, autoload=True,oracle_resolve_synonyms=True)

我收到以下错误:

AssertionError: There are multiple tables visible to the schema, you must specify owner

你能否理解我到底出错的地方。

谢谢,

罗希特夏尔

4 个答案:

答案 0 :(得分:7)

from sqlalchemy import create_engine
import cx_Oracle

host=hostname
port=port
sid='sid'
user='username'
password='password'
sid = cx_Oracle.makedsn(host, port, sid=sid)

cstr = 'oracle://{user}:{password}@{sid}'.format(
    user=user,
    password=password,
    sid=sid
)

engine =  create_engine(
    cstr,
    convert_unicode=False,
    pool_recycle=10,
    pool_size=50,
    echo=True
)

result = engine.execute('select * from TABLE')

for row in result:
    print row

这对我有用。也可以像

一样创建连接对象
conn = engine.connect()
conn.close()

可以关闭连接。即使您从本地端口连接到远程数据库,这也可以正常工作。

答案 1 :(得分:3)

假设您的计算机上的Oracle客户端具有有效的tnsnames.ora文件,这对我有用:

SQL> DELETE ORDER_DETAIL WHERE CUSTOMER_ID = 1000;

2 rows deleted.

SQL> SELECT * FROM V_MAIN_ORDER;

CUSTOMER_ID ORDER_PRICE
----------- -----------
       2000         400

SQL>

答案 2 :(得分:2)

您不再需要导入cx_Oracle。较新版本的sqlalchemy模块调用函数cx_Oracle.makedsn()。看看:

from sqlalchemy.engine import create_engine

DIALECT = 'oracle'
SQL_DRIVER = 'cx_oracle'
USERNAME = 'your_username' #enter your username
PASSWORD = 'your_password' #enter your password
HOST = 'subdomain.domain.tld' #enter the oracle db host url
PORT = 1521 # enter the oracle port number
SERVICE = 'your_oracle_service_name' # enter the oracle db service name
ENGINE_PATH_WIN_AUTH = DIALECT + '+' + SQL_DRIVER + '://' + USERNAME + ':' + PASSWORD +'@' + HOST + ':' + str(PORT) + '/?service_name=' + SERVICE

engine = create_engine(ENGINE_PATH_WIN_AUTH)


#test query
import pandas as pd
test_df = pd.read_sql_query('SELECT * FROM global_name', engine)

答案 3 :(得分:0)

当没有tnsnames.ora文件时,这对我有用。

user = 'system'
pwd = 'oracle'
dsn = cx_Oracle.makedsn(
    '192.168.1.105', 49161,
    # service_name='your_service_name_if_any'
)
ora_engine = create_engine(f'oracle+cx_oracle://{user}:{pwd}@{dsn}', echo=True)
ora_engine.connect()