【问题标题】:Checking whether user entered username and password exists in MYSQL database检查用户输入的用户名和密码是否存在于MYSQL数据库中
【发布时间】:2015-07-23 05:00:53
【问题描述】:

我是 python 新手,我正在创建一个程序来检查所需用户输入的用户名和密码是否存在于数据库中。这是代码:

 import mysql.connector
 class data:
 def __init__(self):

    self.usernam = input("Enter user name: ")
    self.password= input("Enter Password: ")

 a=data()
 conn = mysql.connector.connect(host='localhost',user='root',passwd='root',database='user')


 loadname= ("select username from user where username='%s'")
 mycursor=conn.cursor()
 mycursor.execute(a.usernam, loadname)
 usercheck=mycursor.fetchone()
 loadpass= ("select pass from user where pass ='%s'")
 mycursor2=conncursor()
 mycursor2.execute(a.password,loadpass)
 passcheck=mycursor2.fetchone()


 if a.username == usercheck and a.password == passcheck:
     print ("pass")

 else:
     print ("sorry")
 conn.commit()
 conn.close()

我收到以下错误:

   Traceback (most recent call last):
     File "C:\Users\HP\Desktop\2nd.py", line 16, in <module>
     mycursor.execute(a.usernam, loadname)
     File "C:\Python34\lib\site-packages\mysql\connector\cursor.py", line                                 507, in execute
     self._handle_result(self._connection.cmd_query(stmt))
     File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 722, in cmd_query
     result = self._handle_result(self._send_cmd(ServerCmd.QUERY, query))
     File "C:\Python34\lib\site-packages\mysql\connector\connection.py", line 640, in _handle_result
      raise errors.get_exception(packet)
     mysql.connector.errors.ProgrammingError: 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'asaa' at line 1

【问题讨论】:

  • asaa anywhere 在哪里,必须是入口用户名?
  • 是用户输入的用户名。 (顺便说一句,这个 'asaa' 用户名存在于 mysql 表的用户名列中)

标签: python mysql


【解决方案1】:
mycursor.execute( loadname,a.username)

先查询,然后是 args ...

我强烈建议您立即切换到像 sqlalchemy 这样的 ORM

【讨论】:

    【解决方案2】:

    我不知道“mysql.connector”,但如果它作为 MySQLdb 工作,它应该是类似的东西:

    mycursor=conn.cursor()
    mycursor.execute("select username from user where username=%s", a.username)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-12-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2017-01-02
      • 2020-06-07
      相关资源
      最近更新 更多