简体   繁体   中英

CALL a SQL 5.6 routine from a Python script

I'm trying to write a Python script which will anonymise users stored in a production database in bulk. This is using an existing routine which has been used many times before and works fine.

My code looks like this:

with open('users_to_delete.csv', newline='') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',', quotechar='|')
for row in csv_reader:
    user_to_delete = row[0]
    delete_query = """CALL anonymise_accounts(""" + user_to_delete + ');'
    cursor.execute(delete_query, multi=True)
    db_connection.commit()

When running it, the following output is returned:

CALL anonymise_accounts(5308561);
CALL anonymise_accounts(2558082);

However, the accounts don't get anonymised.

I'd appreciate any ideas where I may be going wrong here.

execute() is not execute multiple statements, you try to multi=False and delete the semicolon.

with open('users_to_delete.csv', newline='') as csv_file:
csv_reader = csv.reader(csv_file, delimiter=',', quotechar='|')
for row in csv_reader:
    user_to_delete = row[0]
    delete_query = """CALL anonymise_accounts(""" + user_to_delete + ')'
    cursor.execute(delete_query, multi=False)
    db_connection.commit()
with open('users_to_delete.csv', newline='') as csv_file:
csv_reader = csv.reader(csv_file, delimiter='\n', quotechar='|')
for row in csv_reader:
    user_to_delete = row[0]
    delete_query = """CALL rp_anonymise_ho(""" + user_to_delete + ')'
    cursor.execute(delete_query)
    print(cursor.fetchall())

Make sure your data in the csv is comma delimited. For example, there were only one row with no commas, the code would look like in the above.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM