简体   繁体   中英

Concatenate string with another that contains a variable

I have a MySQL query in Python using MySQLdb that I want to give me a different number of rows depending on if there is a LIMIT provided or not.

So, something like:

sql = "SELECT URL, Name AS Category 
       FROM sitelist sl 
       INNER JOIN sitecategory sc ON sc.PlacementCategory_id = sl.Category_id "
if limit > 0 :
    sql += "LIMIT %s", (limit)

However, this fails:

TypeError: cannot concatenate 'str' and 'tuple' objects

How would I be able to concatenate the string containing the limit number while keeping the query 'safe'? In the case of the above being an individual string, the above works correctly.

In PHP, I would simply use a prepared PDO statement with bindparam() , but I cannot find anything similar in Python.

I think the neatest way to do this is:

sql = ("SELECT URL, Name AS Category "
       "FROM sitelist sl "
       "INNER JOIN sitecategory sc ON sc.PlacementCategory_id = sl.Category_id")

if limit > 0:
    whatever.execute(sql+" LIMIT %s", (limit,))
else:
    whatever.execute(sql)

Note that: sql should have opening and closing quotes on every line; and limit needs to be in a tuple as an argument to execute .

use string formatting.

sql = "SELECT URL, Name AS Category\n\
   FROM sitelist sl\n\
   INNER JOIN sitecategory sc ON sc.PlacementCategory_id = sl.Category_id "
if limit > 0: # you don't need parenthesis in python
    sql += "LIMIT {}" .format(limit)

or use format specifier .

sql = "SELECT URL, Name AS Category\n\
       FROM sitelist sl\n\
       INNER JOIN sitecategory sc ON sc.PlacementCategory_id = sl.Category_id "
if(limit > 0):
    sql += "LIMIT %d" %limit

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM