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 = subprocess.run(['mysql', '-hlocalhost', '-uUSER', '-pP@$$WORD123'], stdin=input_file, capture_output=True) print(result)
We simply have a function in which we open our Sql script file and then run it using the
subprocess.run()‘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:
subprocess.run(args, *, 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, subprocess.run vs subprocess.popen
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.