I’m coming from PHP background. When composing SQL queries I tend to do something like this:
$query = '
SELECT
*
FROM `table` AS t
WHERE
t.`categoryID` = '.$categoryID.'
';
if(!empty($recordID))
{
$query .= '
AND t.`recordID` = '.$recordID.'
';
}
$data = $db->fetchAll($query);
What would be the best/most efficient way of doing this in Python?
There are many way you can achieve it using Python. The simplest would be to either use the format string syntax or the Template object.
The advantage of the format string syntax is that you don’t need to use another object. Example:
Although most of the time the database Python wrapper will let you make it more secure (preventing SQL injection):
You maybe interested in these links:
Here is how it can work for Postgresql: