繁体   English   中英

使用pyodbc DSN连接将DataFrame写入Hive

[英]Write DataFrame to Hive using pyodbc DSN connection

如何使用 pyodc 连接将 dataframe 写入 hive 表。 写入时会出现编程错误。从本地将数据写入 hive 的任何其他方式。

错误

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)

您正在将原始(DBAPI) pyodbc.Connection给 pandas 的to_sql 正如to_sql 的文档所述,这样的Connection object 被假定为 sqlite3 连接,因此to_sql正在发送查询

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

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

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

我使用此源将 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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM