2011-09-09 86 views
1

嗨,我有以下的Python:为什么不执行这个sql脚本?

c = conn.cursor() 

#get the account id for the specific user 

actidSQL = "select id from accounts where user_id = (select id from auth_user where username = '%s');" % user 
c.execute(actidSQL) 
actid = c.fetchone()[0] 
print actid 

#fill the latencies table - currently not firing, not sure why? 
latencies_sql = "insert into latencies(account, replier, sender, replyemail, origemail, replydate, origdate) select m1.account, c1.id as replier, c2.id as sender, m1.id as replyemail, m2.id as origemail, m1.date as replydate, m2.date as origdate from contacts c1, contacts c2, emails m1, emails m2 where m1.id > m2.id and m1.reply = m2.mid and m1.reply is not null and c1.id = m1.fr and c2.id = m2.fr and m1.account = %s and m1.account = m2.account;" % (actid) 
print latencies_sql 
c.execute(latencies_sql) 

第一个SQL执行,但第二次却没有。为什么有这个原因?

+0

你确定你的“select m1.account ...”返回任何东西吗? – mojuba

+0

我打印出sql查询,然后直接在数据库上运行它,它可以工作。 – locoboy

+1

您的查询需要注射。更好地使用'c.execute(actidSQL,user)'resp。 'c.execute(actidSQL,actid)'并在查询中保留'%s',而不使用'%'操作符。 (我假设它是MySQL,其他数据库可能需要'?'而不是'%s'。) – glglgl

回答

1

你是什么意思与插件运行或者2次的查询,或1.5查询“第一个sql执行,但第二个没有。”?你得到一个错误?或者数据库中没有数据?我假设数据库中没有数据,并且您正在使用MySQL。这是因为你不承诺你的改变。脚本末尾的conn.commit()应该有所帮助。

+0

宾果。我认为这是问题。 – locoboy

0

它看起来像一个无效的查询问题。你想在同一c.execute

要么你想

insert into latencies(account, replier, sender, replyemail, origemail, replydate, origdate) 

还是一个选择

select m1.account, c1.id as replier, c2.id as sender, m1.id as replyemail, m2.id as origemail, m1.date as replydate, m2.date as origdate from contacts c1, contacts c2, emails m1, emails m2 where m1.id > m2.id and m1.reply = m2.mid and m1.reply is not null and c1.id = m1.fr and c2.id = m2.fr and m1.account = %s and m1.account = m2.account;" 
+0

因此,当我打印出来的控制台,然后手动运行它就像是,它似乎工作正常。 – locoboy

+0

我也这么认为。 –

+1

@Joe号他希望将查询结果插入表中。这通常应该完美地工作。 – glglgl