蟒蛇。使用PK将数据追加到现有表并保持当前数据类型

时间:2019-02-04 09:50:17

标签: python-3.x mysql-python pandasql

我设法成功地将数据追加到具有2个PK的MySQL表中,但是,这样做时,现有的数据类型将变为熊猫选择的数据类型。

这就是我在做什么:

1-定义,用于在写入数据库之前添加PK(在另一个StackOverflow帖子中找到)

def to_sql_k(self, frame, name, if_exists='fail', index=False,
           index_label=None, schema=None, chunksize=None, dtype=None, **kwargs):
    if dtype is not None:
        for col, my_type in dtype.items():
            if not isinstance(to_instance(my_type), TypeEngine):
                raise ValueError('The type of %s is not a SQLAlchemy '
                                 'type ' % col)

    table = pd.io.sql.SQLTable(name, self, frame=frame, index=index,
                     if_exists=if_exists, index_label=index_label,
                     schema=schema, dtype=dtype, **kwargs)
    table.create()
    table.insert(chunksize)

pandas_sql = pd.io.sql.pandasSQL_builder(engine) *引擎设置良好,可用于其他脚本。

2-将DF写入DB:

to_sql_k(pandas_sql, DF, 'TableName',
        index=False, keys=('Column1', 'Column2'), if_exists='replace')

I.E。运行此命令后,数据类型将更改:

varchar(100)转换为文本

int(1)到bigint(20)

varchar(45)转换为文本

甚至是文本的日期时间(这很奇怪,因为如果我执行df.dtypes,它的确会说datetime64 [ns]

任何帮助将不胜感激。

0 个答案:

没有答案