如何在Django中执行MySQL的连接查询?

时间:2017-12-13 09:12:07

标签: python mysql django

我在终端中完美运行的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= "auxesis");

现在我尝试在Django中使用它:

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()

但是它不起作用。那么任何人都可以帮助我吗?

1 个答案:

答案 0 :(得分:1)

您正在尝试使用字符串格式来构建SQL查询。不要这样做,使用参数化查询。如果这样做,则不会在占位符周围添加引号,数据库连接器将为您处理参数的转义。只需将参数作为元组传递:

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()