With bash I can extract the whole database with this command:
DataBaseQuery="SELECT * FROM my_database_list.database"
mysql -uUSER -p'PASSWORD'<< EndOfFile
$DataBaseQuery
EndOfFile
What would be the python equivalent of this command?
With bash I can extract the whole database with this command:
DataBaseQuery="SELECT * FROM my_database_list.database"
mysql -uUSER -p'PASSWORD'<< EndOfFile
$DataBaseQuery
EndOfFile
What would be the python equivalent of this command?
from subprocess import Popen, PIPE
# Create a new process with the provided arguments:
# - the command itself and its arguments as a list
# - create a new pipe for STDIN and STDOUT and STDERR
cmd = Popen(
['mysql', '--user=USER', '--password=Password'],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
)
# Feed the query into STDIN and read STDOUT/STDERR into
# the appropriate variables, which are returned as strings
stdout, stderr = cmd.communicate(
'SELECT * FROM my_database_list.database'
)
You can use subprocess.check_output():
import subprocess
result = subprocess.check_output(
['mysql', '-uUSER', '-pPASSWORD'],
input=b'SELECT * FROM ...')
You must be aware of a problem, however: both with this solution and with the Bash solution, you are specifying the password on the command line. An unprivileged user may use ps
to get the password of your database, thus decreasing security.
Also, note that with Python you can choose from a number of database drivers (such as MySQLdb) and Object Relational Mappers (such as SQLAlchemy). These drivers/ORMs solve the password problem and offer you easy ways to parse results from queries, along with other benefits.
Check out this example from MySQL offical documentation to see how convenient a database driver is.