我想在postgresql中将数据从一个表传输到另一个表

问题描述 投票:0回答:2

我正在制作一个 nft 网站的副本以供练习,但在使用 python 将数据从一个表传输到 postgresql 数据库中的另一个表时遇到错误。发件人表:collection_stats 接收表: tbl_general_assets

`
import psycopg2

db_config = {
    "host": "SECRET",
    "port": SECRET,
    "database": "SECRET",
    "user": "SECRET",
    "password": "SECRET"
}

try:
    connection = psycopg2.connect(**db_config)
    cursor = connection.cursor()
    print("veritabanına bağlantı tm")
except (Exception, psycopg2.Error) as error:
    print("veritabanına bağlanırken hata", error)

select_query = "SELECT * FROM collection_stats"
cursor.execute(select_query)
collection_stats_data = cursor.fetchall()

for row in collection_stats_data:
    insert_query = """
    INSERT INTO tbl_general_assets (
        collection_id, address, network, source, 
        owner_count, unique_owner_count, nft_count, listing_nft_rate, 
        one_day_change_volume, one_day_change_rate, seven_day_change_volume, seven_day_change_rate, 
        thirty_day_change_volume, thirty_day_change_rate, volume_top_bid, floor_price
    ) VALUES (
        %f, %f, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s
    )
   """

    cursor.execute(insert_query, (
        row['collection_id'], row['address'], row['network'], row['source'],
        row['owner_count'], row['unique_owner_rate'], row['nft_count'], row['listing_nft_rate'],
        row['one_day_change_volume'], row['one_day_change_rate'], row['seven_day_change_volume'], row['seven_day_change_rate'],
        row['thirty_day_change_volume'], row['thirty_day_change_rate'], row['volume_top_bid'], row['floor_price']
    ))


connection.commit()
connection.close()
`

输出: veritabanına bağlantı tm 回溯(最近一次调用最后一次): 文件“C:\Users atuh\PycharmProjects\pythonProject tl.py”,第 35 行,位于 row['collection_id'], row['address'], row['network'], row['source'], 类型错误:元组索引必须是整数或切片,而不是 str

python database postgresql psycopg2
2个回答
0
投票

默认情况下,psycopg2 将行返回为 Python 元组(只能按整数索引)。如果要按名称访问列,则必须使用替代游标类,该类将行返回为字典或类似字典的对象。这在文档的“psycopg2.extras”部分的“连接和光标子类”小节中进行了描述。

话虽如此,您确实意识到这可以通过

INSERT INTO tbl_general_assets (foo, bar, fie) SELECT foo, bar, fie FROM collection_stats
更有效地完成,不是吗?


-2
投票
ssh production
pg_dump -C -Fp -f dump.sql -U postgres psycopg2
scp dump.sql development:
rm dump.sql
ssh development
psql -U postgres -f dump.sql
© www.soinside.com 2019 - 2024. All rights reserved.