【问题标题】:Write DataFrame to Hive using pyodbc DSN connection使用 pyodbc DSN 连接将 DataFrame 写入 Hive
【发布时间】:2020-11-04 09:45:21
【问题描述】:

如何使用 pyodc 连接将数据帧写入配置单元表。写入时会出现编程错误。任何其他方式将数据从本地写入配置单元。

错误

Error                                     Traceback (most recent call last)
C:\ProgramData\Anaconda3\lib\site-packages\pandas\io\sql.py in execute(self, *args, **kwargs)
   1430             else:
-> 1431                 cur.execute(*args)
   1432             return cur

Error: ('HY000', "[HY000] [Cloudera][ImpalaODBC] (110) Error while executing a query in Impala: [HY000] : ParseException: Syntax error in line 1:\n...ERE type='table' AND name=?;\n                             ^\nEncountered: Unexpected character\nExpected: CASE, CAST, DEFAULT, EXISTS, FALSE, IF, INTERVAL, LEFT, NOT, NULL, REPLACE, RIGHT, TRUNCATE, TRUE, IDENTIFIER\n\nCAUSED BY: Exception: Syntax error\n (110) (SQLPrepare)")

在处理上述异常的过程中,又发生了一个异常:

DatabaseError                             Traceback (most recent call last) <ipython-input-8-9f82c88c3a27> in <module>
      1 import pyodbc
      2 with pyodbc.connect("DSN=*****", autocommit=True) as conn:
----> 3     df.to_sql(name='Xyz', con=conn, schema='fgh',if_exists='append',index=False)

【问题讨论】:

  • 您好,请在此处显示您的错误,以便其他人更容易回答:)
  • 用错误更新了问题

标签: python pandas hive sqlalchemy pyodbc


【解决方案1】:

您正在将原始 (DBAPI) pyodbc.Connection 传递给 pandas 的 to_sql。正如documentation for to_sql 所述,这样的Connection 对象被假定为sqlite3 连接,因此to_sql 正在发送查询

SELECT name FROM sqlite_master WHERE type='table' AND name=?;

查询数据库。这不适用于 Hive(或 SQLite 以外的任何数据库)。

对于任何其他数据库,您需要传递 to_sql 一个 SQLAlchemy EngineConnection 对象作为 con= 参数。

【讨论】:

    【解决方案2】:

    我使用此源将 df 写入 Hive: https://docs.microsoft.com/en-us/sql/machine-learning/data-exploration/python-dataframe-sql-server?view=sql-server-ver15

    假设您的 df 有两列,您可以使用以下代码: 您需要确保您的表存在于数据库中。

    for index, row in df.iterrows():
        writing_query = """
            INSERT INTO 
                table_name
            VALUES ('{}','{}')
            """ .format(row[0], row[1])
    
        conn = pyodbc.connect("DSN=*****", autocommit=True) # Creates a connection with the database
        cursor = conn.cursor()  # Creates a cursor
        cursor.execute(writing_query) # Asks the cursor to execute the query
        conn.close() # Closes the connection
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-08-02
      • 2022-09-24
      • 1970-01-01
      • 2020-01-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多