Python MySQL:如何从模块中的数据库中读取数据,并将其与主程序中的input()进行比较?

Python MySQL:如何从模块中的数据库中读取数据,并将其与主程序中的input()进行比较?,python,mysql,Python,Mysql,例如,在数据库的“我的用户”表中,有一个值为10的列num 主程序: import mysql x = input() read = mysql.readinput() if x == read: print("Hello, #10!") else: print("bye") 下面是mysql.py模块中的示例代码: import MySQLdb def readinput(): db = MySQLdb.connect("localhost","testuser",

例如,在数据库的“我的用户”表中,有一个值为10的列num

主程序:

import mysql

x = input()    
read = mysql.readinput()

if x == read:
  print("Hello, #10!")
else:
  print("bye")
下面是mysql.py模块中的示例代码:

import MySQLdb

def readinput():
  db = MySQLdb.connect("localhost","testuser","123","database" )
  cur = db.cursor()
  cur.execute("""SELECT * FROM users""") #this may be incorrect
  #(reading of the value of column "num" (which is 10 in my example)) I don't know what to put here, hence my question
我应该在mysql.py中添加什么代码,以便我的主程序可以读取和比较指定用于读取的数据库中的输入和值,以用于if。。。还有别的吗

更新:打印阅读显示:

这些基本上是表users中列first_name中的值

我想做的是,当提示输入时,如果输入了10,它会打印Hello,10!如果没有,那么再见。

您需要使用fetchall函数来获取查询结果。像这样:

import MySQLdb

def readinput():
  db = MySQLdb.connect("localhost","testuser","123","database" )
  cur = db.cursor()
  cur.execute("""SELECT * FROM users""")
  # use fetchall to get all the return results which is a list object
  return cur.fetchall()
import mysql

x = input()    
read = mysql.readinput()
print read
for item in read:
    if str(x) == item[0]:
      print("Hello, #10!")
      break
    else:
      print("bye")
然后在主程序中,您必须比较此列表中的每个项目以显示最终结果。像这样:

import MySQLdb

def readinput():
  db = MySQLdb.connect("localhost","testuser","123","database" )
  cur = db.cursor()
  cur.execute("""SELECT * FROM users""")
  # use fetchall to get all the return results which is a list object
  return cur.fetchall()
import mysql

x = input()    
read = mysql.readinput()
print read
for item in read:
    if str(x) == item[0]:
      print("Hello, #10!")
      break
    else:
      print("bye")

这还会从其他列中获取其他值吗?如果有其他列的值也为10,该怎么办。。因为我认为列num不是specified@shindonism然后,只需更改sql命令即可从用户中选择num。不需要更改python代码。@shindonism我在代码中添加了“打印读取”。告诉我打印出了什么。我编辑它以从用户中选择first_name,而print read显示的是first_name列中的值。。程序的输出没有打印读取:>>10>>bye>>bye>>bye>>bye>>bye>>bye我认为它打印了列first\u name中的值数或行数=6。@shindonism这是否回答了您的问题?