python-3.x - 使用 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)
解决方案
让我们试试这个方法:
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)
推荐阅读
- php - PHP Unit / Mockery - 模拟静态函数不起作用
- json - Python - 解析 JSON 结果
- wolfram-mathematica - 如何在 Mathematica 中输入此公式
- html - 想要使用 jquery 获取 url 特定值
- python - 如何检查 URL SSL 是否让我们以编程方式加密?
- pandas - 多索引熊猫图中时间序列的 X 刻度标签
- php - hex2bin 与 PHP 中的 PASSWORD_DEFAULT 算法的密码哈希值相等吗?
- django - 将 DRF api 与 Vanilla Django 一起使用的任何好的资源?
- r - Inner_join 和过滤,消失的观察
- c++ - 如何在此请求中使用 libcurl 并获取 json server answer c++?