Question

I have a mysql table, which stores some sql queries.

The schema is like:

CREATE TABLE `queries` (`qry_id` int(11) NOT NULL AUTO_INCREMENT,
`qry_text` varchar(2000) COLLATE utf8_unicode_ci NOT NULL,
`result_table` varchar(45) COLLATE utf8_unicode_ci DEFAULT NULL,
`last_run` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP,
`period` int(11) DEFAULT NULL,
`error` tinyint(1) DEFAULT NULL,
PRIMARY KEY (`qry_id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;

For example, one qry text is SELECT * FROM TABLE WHERE COL1 = '%s' and COL2 = '%s'

In python, I pulled a str called qry from a sql table.

qry = "SELECT * FROM TABLE WHERE COL1 = '%s' and COL2 = '%s' "

What I want is:

qry = """SELECT * FROM TABLE WHERE COL1 = '%s' and COL2 = '%s' """ % (var1, var2)

How to artificially add triple quotes around qry and append % (var1, var2) to it. I need to pass qry (in the format I specified) to an API to run. Thanks!

Was it helpful?

Solution

I don't understand your problem:

def get_dangerous_query():
    # do some database access
    # For a demo, just return what we know the table contains
    return "SELECT * FROM TABLE WHERE COL1 = '%s' and COL2 = '%s'"

qry = get_dangerous_query() % (var1, var2)

""" vs " only has an effect on string literals. Quotes are completely meaningless if a string comes from an external source.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top