J2015
J2015

Reputation: 330

Python dynamic query in mysql

I am using python mysql to grab the data from the database. But I don't know how to merge three very similar queries in one single query.This is my code:

if self.X and not self.Y:
        query = """
            SELECT tb1.email
            FROM table1 as tb1
            join table2 as tb2 ON tb2.id= tb1.p_id
            WHERE tb2.id={}
            """.format(self.X)

elif self.X and self.Y:
      query = """
            SELECT tb1.email
            FROM table1 as tb1
            join table2 as tb2 ON tb2.id= tb1.p_id
            WHERE tb2.id={}
            AND tb1.id ={}
            """.format(self.X, self.Y)
else:
    query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb1.id={}
        """.format( self.Y)

As you see the only difference between three queries is in one line. How can I make my code more solid?

Upvotes: 1

Views: 83

Answers (2)

RomanPerekhrest
RomanPerekhrest

Reputation: 92854

Simply (append to a query):

query = """
    SELECT tb1.email
    FROM table1 as tb1
    join table2 as tb2 ON tb2.id= tb1.p_id
    WHERE {}.id = {}
    """

if self.X:
    query = query.format('tb2', self.X)
    if self.Y: query += f' AND tb1.id = {self.Y}'
elif self.Y:
    query = query.format('tb1', self.Y)

Upvotes: 1

Like this ?

if(self.X):
    query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb2.id=%s
        %s"""%(self.X,"AND tb1 = %s"%(self.Y) if self.Y else "")

This will works perfectly but if self.X and self.Y different from integer 0 value because integer 0 equal to boolean False. in this use this code

if(type(self.X)==int):
        query = """
        SELECT tb1.email
        FROM table1 as tb1
        join table2 as tb2 ON tb2.id= tb1.p_id
        WHERE tb2.id=%s
        %s"""%(self.X,"AND tb1 = %s"%(self.Y) if type(self.Y)==int else "")

Upvotes: 0

Related Questions