【问题标题】:how to specify database name in sqlalchemy Teradata connection string?如何在 sqlalchemy Teradata 连接字符串中指定数据库名称?
【发布时间】:2020-12-11 01:20:45
【问题描述】:

我在 Python 脚本中使用 SQLAlchemy。我可以运行选择查询但无法插入,因为它无法识别数据库名称。似乎 Teradata 没有架构概念,因此您会说“数据库 some_db”。

import sqlalchemy
conn_string = 'teradata://' + user + ':' + passw + '@' + host + '/?authentication=LDAP'
eng = sqlalchemy.create_engine(conn_string)
df.to_sql('db_name.my_table', con = eng, if_exists = 'replace', index=False)

这给了我一个错误

The user does not have CREATE TABLE access to database (the default DB)

但那是因为没有指定数据库,我正试图弄清楚该怎么做。我可以像这样进行选择查询:

# execute sql
sql = 'select top 10 * from db_name.some_table'
result = eng.execute(sql)

for x in result:
    print(x)

我尝试这样做,但没有帮助:

eng.execute('database db_name')

仅供参考,此脚本使用 sqlalchemy-teradata。我检查了文档,但并没有真正说明这一点:

https://downloads.teradata.com/tools/articles/teradata-sqlalchemy-introduction

我也尝试将数据库放入连接字符串,但似乎被忽略了:

conn_string = 'teradata://' + user + ':' + passw + '@' + host + ':1025' + '/database=db_name' + '/?authentication=LDAP'

【问题讨论】:

  • 在这种情况下,df.to_sql('db_name.my_table', con = eng, if_exists = 'replace', index=False)db_name 而不是 some_db?这里的数据库是什么:The user does not have CREATE TABLE access to database (some DB name) 不是db_name?所有这些占位符名称都不清楚发生了什么。
  • 但是您指定的是数据库名称 - df.to_sql('db_name.my_table', con = eng, if_exists = 'replace', index=False)
  • 我进行了编辑以使其更清晰。我们称它为 db_name。他们是一样的。它在我执行选择查询时有效,但在我尝试使用 df.to_sql('db_name.my_table'...) 插入时无效。
  • 以这种方式在引擎级别设置默认数据库连接会话,为该会话设置默认数据库,然后断开连接。您需要在同一会话中设置默认值,例如sess=eng.connect() 然后是 sess.execute('database db_name') 并将 sess 代替 eng 传递给 to_sql 方法。

标签: sql python-3.x sqlalchemy teradata


【解决方案1】:

df.to_sql 方法中的 tablename 始终被视为非限定名称。 “模式”概念通过 sqlalchemy 方言映射到 Teradata “数据库”对象。所以只需使用schema= 参数:

df.to_sql('my_table', schema ='db_name', con = eng, if_exists = 'replace', index=False)

【讨论】:

  • 顺便说一句,与 sqlalchemy-teradata 相比,最好使用当前/支持的 teradatasqlalchemy 模块(和 teradatasql 方言)进行新工作teradata 方言;但答案是一样的,除了 URL 参数 authentication=LDAP 变为 logmech=LDAP
猜你喜欢
  • 1970-01-01
  • 2016-10-22
  • 1970-01-01
  • 2012-08-16
  • 1970-01-01
  • 2018-01-10
  • 2019-12-11
  • 2017-06-26
  • 2012-05-20
相关资源
最近更新 更多