Search code examples
pythonpandaspostgresqlpsycopg2

How to save many files with specific ids where ids are in int8 format using psycopg2?


I need to get data from a table "entries" in a database where i already have a dataframe of specific instances (log_id) in attribute "file_id". The problem is that I cant ask for int8 in iteration mode for example the code below doesn't work how to save each file in the iteration.

log_id ={DataFrame:(4,1)}

for item in log_id[0]:
    extract = ' SELECT * From "entries" WHERE "Entries"."file_id" 
    = ??;'
    b=cur.execute(extract, [item])
    writer = pd.ExcelWriter('log'+item+'.xlsx', engine='xlsxwriter')
    b.to_excel(writer, index=False)
    writer.save()

Solution

  • This works fine!

    for item in logid_r[0]:
    
        cur.execute('SELECT * FROM "entries" WHERE "entries"."file_id" = %(int)s;',  {'int': item} )
    
        datapoints = cur.fetchall()
        cols = [desc[0] for desc in cur.description]
        datalog = pd.DataFrame(datapoints, columns=cols) 
        writer = pd.ExcelWriter('log' + str(item) + '.xlsx', engine='xlsxwriter')
        datalog.to_excel(writer, index=False)
        writer.save()