I'm trying to import some CSV files to a table on a MySQL database. The CSV files are updated daily and my intention is to use this program in python to automate the process. The idea is: if the information already exists, I want to update it. If the information doesn't exist, I want to insert the data.
But I'm having this error:
AttributeError 'DictCursor' object has no attribute 'update'
Thanks in advance.
csv_data = csv.reader(open('ATEG_REGIONAL_MG_DADOS_TB_ATIVIDADE.csv', encoding='ISO-8859-15'), delimiter=';')
next(csv_data)
for row in csv_data:
for i, l in enumerate(row):
if row[i] == '':
row[i] = None
cursor.execute('SELECT * FROM atividade WHERE CD_ATIVIDADE=%s', row[0])
if cursor.fetchall():
cursor.update('UPDATE atividade WHERE CD_ATIVIDADE = row[0]'),
else:
cursor.execute('INSERT INTO atividade (CD_ATIVIDADE, NM_ATIVIDADE, ST_ATIVO, COD_USUARIO_INCLUSAO, COD_USUARIO_ALTERACAO, DAT_INCLUSAO, DAT_ALTERACAO, CO_ATIVIDADE_REZOLVE, ROWID, FLG_SAFRA, FLG_PRODUTIVO, FLG_TIPO_ATIVIDADE, FLG_INDICADOR_ISA) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', row)
# close the connection to the database.
db.commit()
cursor.close()
print("Imported!")
CodePudding user response:
If you are using psycopg2, there is no cursor.update()
function present. Try cursor.execute()
instead.
Also row[0] is considered as a string in your query. So, change it to:
cursor.execute('UPDATE atividade WHERE CD_ATIVIDADE = ' row[0])
CodePudding user response:
Seems like you are confusing two different libraries.
import MySQLdb
and from flask_mysqldb import MySQL
are two different libraries.
Since you are using flask
adding this line app.config['MYSQL_CURSORCLASS'] = 'DictCursor'
and then calling the cursor cursor=db.connection.cursor()
should solve your problem.
Taken from the official git page