In order to connect with a MySql database by logging in and then running an Sql script, you can use the following code:

import subprocess

def createNewDatabase():
    with open('/pathToFile.sql') as input_file:
        result =['mysql', '-hlocalhost', '-uUSER', '-pP@$$WORD123'], stdin=input_file, capture_output=True)

We simply have a function in which we open our Sql script file and then run it using the method.‘s first argument is the name of the command, followed by an array of arguments supported by the command. Then there are optional keyword arguments:, *, stdin=None, input=None, stdout=None, stderr=None, capture_output=False, shell=False, cwd=None, timeout=None, check=False, encoding=None, errors=None, text=None, env=None, universal_newlines=None)

Credits: Running Sql commands in Python, vs subprocess.popen

python mysql script: How to load mysql script in python. Python tutorial to load mysql scripts


This post shows how to run MySql script in Python. The MySql script is placed as a file on the system which is subsequently loaded and executed by Python.