Python SQL查询中的while循环

2 投票
1 回答
11156 浏览
提问于 2025-04-17 14:57

你好,我在PHP中试过这个查询,运行得很好,现在我想在Python中做同样的事情。

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

我该如何在Python的查询中使用while循环呢?

1 个回答

3

使用fetchone()方法,或者直接通过游标进行遍历:

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

或者

for row in cursor:
    print row

撰写回答