python 逐一迭代mysql字段的行

标签 python mysql

我正在尝试一个程序,其中有“table=qwes”和“field1=first,field2=second”。我需要获取每一行一次,它必须通过条件“if a row has got hello, then”其为真,否则为假'。

我使用了 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。

最佳答案

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

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]...只需在其运行时对其进行调试,然后查看 j 中的内容通过 for 循环..如果这不起作用,应该是一个简单的修复

关于python 逐一迭代mysql字段的行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24432831/

相关文章:

python - QFrame 不以 QWidget 作为父级?

php - 将 mySQL 数据库的行链接到引用的页面

php - php mysqli_connect : authentication method unknown to the client [caching_sha2_password]

mysql - 在 WHERE 和 AND 上使用 "not in"?

python - 迭代器卡住

python - 如何将 CRC16-CCITT 算法的 C++ 代码转换为 Python 代码?

python - 为什么我得到 "' ResultSet' has no attribute 'findAll'“在 Python 中使用 BeautifulSoup?

mysql - 无法理解案例陈述

MySql 获取具有最新日期的行

python - 在 python 中解析 facebook graph api json 时遇到问题