I use the Python psycopg2 module to copy the content of a csv file (a list of users) into a PostGreSQL database.
So I begin to parse the CSV with the Python pandas module. Then with a for loop, I try to insert my data in my SQL queries.
I have two problems :
a) When I execute the role query (query 2 - see below) to create new roles in the database, I get 'user' instead of user. How could I do to insert the roles with the right syntax ?
b) The queries 3 and 4 (see below) give the following error :
TypeError: not all arguments converted during string formatting
What is exactly this problem and how to solve it ?
Here is the complete code :
import csv, psycopg2
import pandas as pd
conn = psycopg2.connect("host=localhost dbname=vmap user=postgres password=postgres port=5432")
c = conn.cursor()
# Import_CSV
data = pd.read_csv (r'users.csv', sep=';')
df = pd.DataFrame(data, columns= ['id','login','mdp','mail','date'])
print(df)
for row in df.itertuples():
print (row.login)
c.execute("INSERT INTO users (user_id, login, email) VALUES(%s, %s, %s);", (row.id, row.login, row.mail))
# query2
c.execute('create role "%s" with encrypted password %s',(row.login, row.mdp))
# query3
c.execute('grant vitis_user, vmap_user to "%s"',(row.login))
# query4
c.execute('grant connect on vmap to "%s"',(row.login))
And the DataFrame I want to parse (content of the CSV file) is this one :
id login ... mail date
0 10 ldeschamps-diallo ... [email protected] 2022-01-31
1 11 pmarion ... [email protected] 2022-01-31
2 12 cleroy ... [email protected] 2022-01-31
3 13 lcourtois ... [email protected] 2022-01-31
4 14 rpaul-monnier ... [email protected] 2022-01-31
pandaswhen you can use copy_from directly frompsycopg2. It would be a lot quicker.