【问题标题】:Unable to write data to Vertica Database using Python SqlAlchemy - Type "TEXT" does not exist无法使用 Python SqlAlchemy 将数据写入 Vertica 数据库 - 类型“TEXT”不存在
【发布时间】:2018-07-10 08:28:04
【问题描述】:

我正在尝试将 pandas 数据框上传到 Vertica 数据库 能够使用 sqlalchemy 设置引擎和查询数据库。

但是当我尝试从 pandas 数据帧上传数据时,由于类型“TEXT”不存在而收到错误消息。我使用的是 Windows 10,并创建了 ODBC 连接。

import sqlalchemy as sa
engine = sa.create_engine('vertica+pyodbc:///?odbc_connect=%s' %(urllib.parse.quote('DSN=TESTDB'),))
sql_query = "select * from sample_table"
df = pd.read_sql_query(sql_query, con=engine) # this works, get the data as required in the dataframe
*df.apply[Do various data transformations as required]*

# Write back to the database
df.to_sql(name='sample_table_cleaned', con = engine, schema = "Dev" , if_exists = 'append', index = True)

上面的代码 (df.to_sql) sn-p 出现错误:ProgrammingError: (pyodbc.ProgrammingError) ('42704', '[42704] ERROR 5108: Type "TEXT" does not exist \n (5108) (SQLExecDirectW)')

任何人都可以帮助解决这个问题,

提前致谢!!

【问题讨论】:

    标签: python pandas sqlalchemy vertica


    【解决方案1】:

    在工作中遇到过类似的事情,并且已经使用 VARCHAR 为字符串对象的列更改了类型

    def updateType(df_para):
        dtypedict = {}  # create and empty dictionary
        for i,j in zip(df_para.columns, df_para.dtypes):
            if "object" in str(j):
                dtypedict.update({i: sa.types.VARCHAR})
    
        return dtypedict
    
    updatedict = updateType(df)  # update the datafraame type
    

    【讨论】:

    • 感谢您的回答,但是您如何处理您的 updatedict 呢?尝试使用 df= df.astype(updatedict) 更改 dtypes 将引发错误 dtype '<class 'sqlalchemy.sql.sqltypes.VARCHAR'>' not understood
    【解决方案2】:

    很好的解决方案@calestini!

    import sqlalchemy as sa 
    
    engine = create_engine('vertica+vertica_python://user:{}@host:5433/db_name')
    
    df.to_sql(name='table_name', schema = 'schema_name', con = engine, if_exists='append', dtype = updatedict, index = False)
    

    这是运行函数后数据类型字典的外观:

    {'custom_index': sqlalchemy.sql.sqltypes.VARCHAR,
     'lastmodifiedbysales': sqlalchemy.sql.sqltypes.VARCHAR,
     'linked_distributor': sqlalchemy.sql.sqltypes.VARCHAR,
     'linked_reseller': sqlalchemy.sql.sqltypes.VARCHAR,
     'number_of_licenses': sqlalchemy.sql.sqltypes.VARCHAR}
    

    谢谢!

    【讨论】:

      猜你喜欢
      • 2021-07-11
      • 1970-01-01
      • 2011-05-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-04-18
      • 2018-11-29
      相关资源
      最近更新 更多