Seth Koberg
Seth Koberg

Reputation: 1055

Running MySQL query from Python 2.4 while not installing modules (MySQLdb)

I need to run a MySQL query from Python 2.4 but I cannot download/install any modules for Python.

The reason I cannot download is because this script is to be run on servers (RedHat) and our customers will not let us download and install anything.

I've been trying to use subprocess, but the query I'm using is giving me a syntax error.

The query works outside of Python if I run it from a query browser, but adding the quotes and commas inside the subprocess command [] makes things a little confusing.

The command I'm trying to run is as follows:

subprocess.call(['mysql', '-D DB', '--user="user"', '--password="password"', '-e', '"SELECT cu, control_name FROM PresetProfile WHERE NOT cu='' AND NOT control_name='' INTO OUTFILE '/directory/for/output.file' FIELDS TERMINATED BY ':' LINES TERMINATED BY '\n';"', shell=True])

The Syntax error I get points to the single quote immediately before the : after FIELDS TERMINATED BY.

  File "<stdin>", line 1
subprocess.call(['mysql', '-D DB', '--user="user"', '--password="password"', '-e', '"SELECT cu, control_name FROM PresetProfile WHERE NOT cu='' AND NOT control_name='' INTO OUTFILE '/directory/for/output.file' FIELDS TERMINATED BY ':' LINES TERMINATED BY '\n';"', shell=True])
                                                                                                                                                                                                                                       ^
SyntaxError: invalid syntax

Once I get this output file created, I can stop using subprocess and get back to regular file processing.

Upvotes: 0

Views: 103

Answers (1)

mgilson
mgilson

Reputation: 309841

Your query is this: '"SELECT cu, control_name FROM PresetProfile WHERE NOT cu='' AND NOT control_name='' INTO OUTFILE '/directory/for/output.file' FIELDS TERMINATED BY ':' LINES TERMINATED BY '\n';"'

Notice that you have ' inside your string -- you'll need to escape them or use triple quotes.

'"SELECT cu, control_name FROM PresetProfile WHERE NOT cu=\'\' AND NOT control_name=\'\' INTO OUTFILE \'/directory/for/output.file\' FIELDS TERMINATED BY \':\' LINES TERMINATED BY \'\\n\';"'

Also you'll probably want to drop the shell=True bit -- Managing the escaping is hard enough if you're only dealing with Python. Once you need to un-escape it again for the shell things get even more messy.

Upvotes: 1

Related Questions