python迭代行逐个mysql字段

时间:2014-06-26 14:11:39

标签: python mysql

我正在尝试一个程序,我有' table = qwes'和' field1 = first,field2 = second"。我需要达到每一行,这必须通过条件'如果一行已经打招呼,那么它的真假其他错误'。

我使用了limit并且需要增加偏移量,然后它必须循环返回下一行查找true或false。同样,它应该结束,直到所有行都完成。

import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

cursor = db.cursor()

qas = 0

while(qas < 100)
qas = qas + 1
posts = "select * from ques LIMIT 1 OFFSET %s " %(qas)

cursor.execute(posts)
db.commit()
keywords=[]
a='hello'
for i in cursor_posts.fetchall():
    keywords.append(i[0])
    if a in keywords:
      print true
    else:
      print false 
    raw_input("please press enter to continue") 

请帮我修理我的程序;我希望while循环执行,直到行可用。由于我缺乏知识,我默认为100。

1 个答案:

答案 0 :(得分:1)

我的建议是做这样的事情:

import MySQLdb
db = MySQLdb.connect(host="localhost", # your host, usually localhost
                     user="root", # your username
                      passwd="mysql", # your password
                      db="sakila") # name of the data base

cursor = db.cursor()
posts = "select * from ques LIMIT 100"
cursor.execute(posts)
db.commit()
a='hello'
counter = 0

for j in cursor.fetchall():
    counter += 1
    if a in j[0]:
      print ("Row " + str(counter) + "= " + j[0] + " => True")
    else:
      print ("Row " + str(counter) + "= " + j[0] + " => False") 
    raw_input("please press enter to continue") 

基本上用100条记录查询数据库...然后遍历执行语句的fetchall()并检查是否&#39; hello&#39;在j [0]中你的帖子将是...假设数据库中的第一列是帖子...如果它是一个id然后将其移动到j [1] ...只需对它运行调试当你进行for循环时看看j中的内容..如果这不起作用,应该是一个简单的修复