I have the following lines of code:
sql = \"source C:\\\\My Dropbox\\\\workspace\\\\projects\\\\hosted_inv\\\\create_site_db.sql\"
cursor.execute (sql)
I believe the "source" command is specific to the mysql shell executable - it is not an sql command and cannot be interpreted correctly when executed as an sql statement.
To achieve your goal, you probably need to read your script file and parse it into individual sql statements, then execute them one at a time with your cursor.
I ran into the same problem!
As a solution I installed the library sqlparse and used the sqlparse.split( sql ) results. I had to check that sql_parts don't include blank lines as solo statements... Otherwise "WOW" sqlparse is pretty great and exactly what I needed!
import sqlparse
....
sql = open("test.sql").read()
sql_parts = sqlparse.split( sql )
for sql_part in sql_parts:
if sql_part.strip() == '':
continue
cursor.execute( sql_part )
FYI: If you do not run each statement on its own you may get the error "Commands out of sync; you can't run this command now". I only got this error after I added some more queries to my sql file - not the first time around.
The source
command is one of the built-in commands recognized only by the mysql command-line client. It is not supported as a statement you can execute via any API.
Some people think you can simply split an SQL script file on the ";
" statement terminator and call execute()
on each line you get. But there are numerous exception cases:
CONNECT
, SOURCE
, CHARSET
, WARNINGS
, QUIT
, etc.;
for example DELIMITER
.;
but not as a terminator, like CREATE TRIGGER
.;
inside string literals or comments or even quoted identifiers.To load an SQL script programmatically, you'd have to duplicate a fair amount of the functionality of the mysql client. So it's best if you just fork a process to actually execute that client program with the script as input.
See also:
As others said, you cannot use the command source
in MySQLdb Python API
So, instead of running that, load the file and execute it
Lets say your .sql file has
create database test;
Read the content like
sql=open("test.sql").read()
And then execute it
cursor.execute(sql);
You will get new database "test"
'source' is not an SQL command, but an internal command of the mysql command line client.