2013-02-06 47 views
0

嗨,我有尝试在运行良好的PHP这个查询和我做同样的事在Pythonwhile循环Python中的SQL查询

$select=mysql_query("SELECT DISTINCT A.entity_id AS entity_id ,A.email AS email,A.catquizid AS style_quiz_score ,A.catquizquesans AS style_quiz_answer,A.created_at AS date_joined,A.is_active AS is_active ,B.attribute_id AS attribute_id,B.value AS info FROM `customer_entity` AS A inner join `customer_entity_varchar` AS B on A.entity_id=B.entity_id WHERE B.`attribute_id` IN (1,2) limit 10",$conn); 

    $arr=array(); 

    while($result= mysql_fetch_assoc($select)) 
     { 
      if(!isset($arr[$result['entity_id']]['lastname'])){ 
       $arr[$result['entity_id']]['firstname'] = $result['info']; 
      } 
      $arr[$result['entity_id']]['lastname'] = $result['info']; 
      $arr[$result['entity_id']]["email"]=$result['email']; 
      $arr[$result['entity_id']]["style_quiz_score"]=$result['style_quiz_score']; 
      $arr[$result['entity_id']]["style_quiz_answer"]=$result['style_quiz_answer']; 
      $arr[$result['entity_id']]["date_joined"]=$result['date_joined']; 
      $arr[$result['entity_id']]["is_active"]=$result['is_active']; 

      $arr[$result['entity_id']]["username"]=normalize_str($result['email']); 
     } 

,并在Python我已经尝试过这种

def customer_migrate(request): 
    cursor = connections['migration'].cursor() 
    cursor.execute("SELECT DISTINCT A.entity_id AS entity_id ,A.email AS email,A.catquizid AS style_quiz_score ,A.catquizquesans AS style_quiz_answer,A.created_at AS date_joined,A.is_active AS is_active ,B.attribute_id AS attribute_id,B.value AS info FROM customer_entity AS A inner join customer_entity_varchar AS B on A.entity_id=B.entity_id WHERE B.attribute_id limit 4 ") 
    row = cursor.fetchall() 

如何使用while循环在Python查询,

+2

为什么这个问题标记为“Django的?你也在寻找django的解决方案吗? – wuher

+1

我在这种情况下使用Django框架工作与python –

+0

,我建议使用django的模型:https://docs.djangoproject.com/en/dev/topics/db/models/它允许您也执行原始的sql查询: https://docs.djangoproject.com/en/dev/topics/db/sql/ – wuher

回答

1

使用fetchone()或只是遍历光标:

row = cursor.fetchone() 
while row is not None: 
    print row 
    row = cursor.fetchone() 

for row in cursor: 
    print row 
+0

我面临的主要问题是别名,我无法获取像行['entity_id']的数据,因为它没有返回字典名称,我已经阅读了文档如何使用字典名称获取数据,但它不适用于我。 NOW我想要的是我在PHP中使用while循环的方式,我可以在python中使用它 –

+0

我已经使用这个desc = cursor.description,并得到了folowing('entity_id',3,2,10,10,0,0 )('email',253,23,765,765,0,0)('style_quiz_score',253,5,765,765,0,0)('style_quiz_answer',252,0,-1,-1, 0,0)('date_joined',12,19,19,19,0,0)('is_active',1,1,1,0,0)('attribute_id',2,1,5,5 ,0,0)('info',253,7,765,765,0,0),我无法理解它的含义 –

+0

@Rohit你使用pyodbc吗?由于您选择的是“AS”,因此您应该可以这样做:'row.entitiy_id' 此外,行的列表顺序与select语句相同,因此您可以使用列表索引。 – Lysergia25