简体   繁体   中英

Importing a MySQL database with a Python script fails when the same command works on the command line, what gives?

I'm running a MySQL server in docker container and am trying to import a .sql file in a Python script (Flask app). This is my code:

os.system("docker exec -i %s_db_1 mysql -u<username> -p<password> <db name> < %s" % (name, db_file))

It returns this error in the terminal the Flask app is running in:

ERROR 1064 (42000) at line 1835: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1

If I run this command from the command line, it works. I can't really figure out how using os.system in this instance is meaningfully different. I've also tried subprocess.call and it produces the same error.

Your MySQL request is not well formatted, are you sure it works on command line ?

You should try:

os.system("docker exec -i {0}_db_1 mysql -u {1} -p {2} {3}".format(db_file, username, password, db_name))

I am using NamedTemporaryFile and it turns out that the file wasn't finished writing to disk when I was trying to use it. If I call db_file.flush() right before os.system everything works.

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