Skip to content
Advertisement

Execute mysql commands in linux terminal using Python

I would like to automate the setup of a database and I would like to do it by using a python script to execute some commands in a linux terminal.

But I cannot see any way of executing commands in the terminal after connection to mysql database.

Below you can see a part of the script:

JavaScript

This starts mysql, and after this none of the commands I try to execute from python get executed.

For example, I would like to run commands like these:

JavaScript

Is this possible?

Edit 1: Potential solution as suggested by @AndHeFallen:

In python I create an sql file named db.sql, then run this in the terminal:

JavaScript

Advertisement

Answer

I don’t think it’s possible to do that. If you want to interact with your MySQL database with a Python script, you’ll need to connect directly to your db with an api like MySQLdb. (I may be wrong but the way you want to do may cause security issues)

Advertisement