【问题标题】:How to insert value in already created Database table through pandas `df.to_sql()`如何通过 pandas `df.to_sql()` 在已创建的数据库表中插入值
【发布时间】:2019-04-19 06:13:31
【问题描述】:

我正在创建新表,然后在其中插入值,因为 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() 中的值插入到数据库表中

【问题讨论】:

  • 错误是什么?也请分享一些数据。
  • 你能在df.to_sql之前打印df吗?
  • @UpasanaMittal df 正在打印
  • @SupratimHaldar 它没有显示错误问题是它没有将数据加载到表中

标签: python-3.x pandas postgresql sqlalchemy


【解决方案1】:

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

我的建议,去掉create_query,处理to_sql()之后的数据类型。创建 SQL 表后,您可以使用实际的 SQL 表,并针对此临时表连接以进行重复测试。非重复项可以写入实际表,转换UPDATE 上的数据类型以匹配表数据类型结构。

【讨论】:

  • 感谢您的回复,抱歉回复晚了,我已经找到了解决此问题的方法,我在读取 csv 文件时在 csv 文件中添加标题,然后将该文件上传到解决了我的问题的数据库。 col_name = ['1st_column', '2nd_column', '3rd_column'] 然后读取csv文件data = pd.read_csv(new_file, delimiter="\t", chunksize=500000, error_bad_lines=False, names=col_name, quoting=csv.QUOTE_NONE, dtype="unicode", iterator=True, header=None)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2017-04-01
  • 1970-01-01
  • 2017-01-17
  • 1970-01-01
  • 1970-01-01
  • 2022-01-09
  • 1970-01-01
相关资源
最近更新 更多