如何通过熊猫`df.to_sql()`

时间:2019-04-19 06:13:31

标签: python-3.x pandas postgresql sqlalchemy

我正在创建新表,然后在其中插入值,因为tsv文件没有标题,因此我需要先创建表结构,然后再插入值。我正在尝试在创建的数据库表中插入值。我正在使用df.to_sql函数向数据库表中插入tsv值,但是在其创建表中,但是它没有在该表中插入值,并且也没有给出任何类型的错误。

我尝试通过sqalchemyinsert值创建新表,该表可以工作,但不适用于已创建的表。

conn, cur = create_conn()

engine = create_engine('postgresql://postgres:Shubham@123@localhost:5432/walmart')

create_query = '''create table if not exists new_table(
                "item_id" TEXT, "product_id" TEXT, "abstract_product_id" TEXT, 
           "product_name" TEXT, "product_type" TEXT, "ironbank_category" TEXT, 
          "primary_shelf" TEXT, apparel_category" TEXT, "brand" TEXT)'''

cur.execute(create_query)
conn.commit()
file_name = 'new_table'
new_file = "C:\\Users\\shubham.shinde\\Desktop\\wallll\\new_file.txt"
data = pd.read_csv(new_file, delimiter="\t", chunksize=500000, error_bad_lines=False, quoting=csv.QUOTE_NONE, dtype="unicode", iterator=True)
with open(file_name + '_bad_rows.txt', 'w') as f1:
    sys.stderr = f1
    for df in data:
        df.to_sql('new_table', engine, if_exists='append')
data.close()

我想将df.to_sql()中的值插入数据库表

1 个答案:

答案 0 :(得分:0)

不确定此参数是否适用于postgresql,但在mssql上执行此操作时遇到类似的问题。 .to_sql()已在new_table中方法的第一个参数中创建了表。 if_exists = append也不检查重复值。如果new_file中的数据被覆盖,或再次通过您的函数运行,它将仅添加到表中。至于为什么看到表名却看不到其中的数据,可能是由于df的大小所致。尝试将fast_executemany=True设置为create_engine的第二个参数。

我的建议是,摆脱create_query,并处理to_sql()之后的数据类型。一旦创建了SQL表,就可以使用实际的SQL表,并针对该登台表进行联接以进行重复测试。可以将非重复项写入实际表,从而转换UPDATE上的数据类型以匹配表的数据类型结构。