Python逐行遍历MySQL字段

0 投票
1 回答
1388 浏览
提问于 2025-04-18 11:11

我正在尝试写一个程序,里面有一个表格叫做 'table= qwes',还有两个字段 'field1= first' 和 'field2= second'。我的目标是检查每一行数据,看看它们是否符合一个条件:如果这一行包含“hello”,那么就算是“真”,否则就是“假”。

我使用了限制(limit),还需要增加偏移量(offset),然后要循环回去查找下一行,判断它是“真”还是“假”。这样一直进行,直到所有的行都检查完为止。

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

请帮我修复我的程序;我希望这个循环能一直执行,直到所有的行都被检查完。因为我对这方面了解不多,所以默认设置了100。

1 个回答

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()结果,检查一下'hello'是否在j[0]中,假设你的帖子就在这里... 如果数据库的第一列是帖子的话,如果是个ID,就把它移到j[1]... 在这个过程中可以进行调试,看看在你遍历for循环时,j里面有什么内容... 如果这样不行,应该很容易修复。

撰写回答