4

I am trying to run following code:

with open('file.sql') as sqlFile:
    sql = sqlFile.read()
    cursor.execute(sql)

file.sql contains some SQL queries that initialize a DB.

However this code finishes working before all queries are proceed. They will be proceed in a few seconds after this script finish working.

How can I wait until all queries are proceed?

1
  • The error happens because next line of code launches an application that use the initialized DB but DB is not initialized completely when the application is starting. Feb 9, 2011 at 18:07

2 Answers 2

3

That's already the case.

execute() command already waits for the command to be completely executed before passing to the next line of code in your script.

That means your code won't continue before the cursor.execute() finishes execution.

Your assumptions are wrong. I assume you're getting an error in your sql execution, and that's what causes the sql to be skipped.

For one, cursor.execute() usually can't run multiple SQL statements, so you probably have to split the file into multiple statements and call cursor.execute() multiple times, one for each statement.

Please remove all try/except clauses that might be hiding errors with the code above, and provide the full error traceback you're getting, if that's not the case.

2
  • It should wait. But it doesn't. I read somewhere that it doesn't wait if there are constructions like this: SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO"; Feb 10, 2011 at 13:38
  • If cursor.execute() is set to run multiple statements (which is possible with schema updates for example) it can happen, and it does for me. E.g. if you do an insert at the end it will only be visible later on, not necessarily at the end of the execute.
    – Maxime
    May 7, 2021 at 7:10
2

I experienced the same problem. I solved it by call mydb.commit() after mycursor.execute Then, it worked. But I am not sure if it is the lege artis construction.

1
  • 1
    Ha! There is the right solution: AUTOCOMMIT mydb = mysql.connector.connect( host="172.18.207.1", user="ABCD", passwd="password", database="DKML", autocommit="True" )
    – RNA
    Feb 18, 2019 at 17:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.