首页 > 解决方案 > 使用 pandas to_sql() 将缺失数据插入到 clickhouse db

问题描述

这是我第一次使用 sqlalchemy 和 pandas 将一些数据插入到 clickhouse 数据库中。

当我尝试使用 clickhouse cli 插入一些数据时,它工作正常,但是当我尝试使用 sqlalchemy 做同样的事情时,我不知道为什么缺少一行。

我做错了什么吗?

import pandas as pd
# created the dataframe

engine = create_engine(uri)
session = make_session(engine)
metadata = MetaData(bind=engine)
metadata.reflect(bind = engine)
conn = engine.connect()
df.to_sql('test', conn, if_exists = 'append', index = False)

标签: python-3.xsqlalchemyclickhouse

解决方案


让我们试试这个方法:

import pandas as pd
from infi.clickhouse_orm.engines import Memory
from infi.clickhouse_orm.fields import UInt16Field, StringField
from infi.clickhouse_orm.models import Model
from sqlalchemy import create_engine


# define the ClickHouse table schema
class Test_Humans(Model):
    year = UInt16Field()
    first_name = StringField()
    engine = Memory()


engine = create_engine('clickhouse://default:@localhost/test')

# create table
with engine.connect() as conn:
    conn.connection.create_table(Test_Humans) # https://github.com/Infinidat/infi.clickhouse_orm/blob/master/src/infi/clickhouse_orm/database.py#L142

pdf = pd.DataFrame.from_records([
    {'year': 1994, 'first_name': 'Vova'},
    {'year': 1995, 'first_name': 'Anja'},
    {'year': 1996, 'first_name': 'Vasja'},
    {'year': 1997, 'first_name': 'Petja'},
    # ! sqlalchemy-clickhouse ignores the last item so add fake one
    {}
])

pdf.to_sql('test_humans', engine, if_exists='append', index=False)

考虑到sqlalchemy-clickhouse忽略最后一项,所以添加一个假的(参见源代码和相关问题 10)。


推荐阅读