2

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?

2
  • 3
    Why not use the built-in ORM? Commented Dec 13, 2017 at 9:12
  • 1
    Plus, you should absolutely not use string interpolation to create SQL commands. Commented Dec 13, 2017 at 9:23

1 Answer 1

1

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()
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.