Parishilan Rayamajhi
Parishilan Rayamajhi

Reputation: 3049

How to execute join queries of MySQL in Django?

My SQL query which runs perfectly in terminal looks like this:

select t.txid, t.from_address, t.to_address, t.value, t.timestamp,
     t.conformations, t.spent_flag,t.spent_txid  from transaction_details t 
    where t.to_address =(select distinct  a.address from address_master a  
    inner join  panel_user p  on a.user = p.user and a.user= "auxesis");

Now I tried using it in Django like this:

sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid  from 
transaction_details t where t.to_address =(select distinct  a.address from
 address_master a  inner join  panel_user p  on a.user = p.user and a.user= "%s" """),%(user)
    cursor.execute(sql)
    res = cursor.fetchall()

But ya its not working. So any one please help me with it?

Upvotes: 2

Views: 523

Answers (1)

mata
mata

Reputation: 69012

You're trying to use string formatting to build an SQL query. Don't do that, use parameterized queries. If you do that, you don't add quotes around the placeholders, the database connector will handle escaping of the parameters for you. Just pass the arguments as a tuple:

sql = """ select t.txid, t.from_address, t.to_address,t.value, t.timestamp, t.conformations, t.spent_flag,t.spent_txid  from 
transaction_details t where t.to_address =(select distinct  a.address from
 address_master a  inner join  panel_user p  on a.user = p.user and a.user = %s """)
cursor.execute(sql, (user,))
res = cursor.fetchall()

Upvotes: 1

Related Questions