如何将python程序与数据库连接?

时间:2018-07-06 07:35:02

标签: python database window

我是python的初学者。我有一个有关访问系统的项目,该系统使用python编码并连接到数据库。当我运行代码时,它不会连接到数据库,我不知道如何将用户输入与数据库值进行比较。

import pymysql,time

def login():
    db = pymysql.connect(host='localhost',user='root',password='',db='ghost')
    cursor = db.cursor()

    while True:
        usercode = input("please enter your usercode: ")
        password = input("please enter your password: ")

        find_user = ("SELECT * FROM `user` WHERE usercode ='$usercode' AND password = '$password'")
        cursor.execute(find_user)
        results = cursor.fetchall()

        if results:
            for i in results:
                print("SUCCESS "+i[2])
            #return("exit")
            break

        else:
            print("usercode and password not recognised")
            again = input("Do you want to try again?(y/n): ")
            if again.lower() == "n":
                print("Goodbye")
                time.sleep(1)
                #return("exit")
                break
login()

为供您参考,我使用了崇高的文字3。在cmd上运行代码时

Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation.  All rights reserved.

C:\Users\Dell Inspiron Mini>D:

D:\>xampp\htdocs\T1.py
please enter your usercode: 7803069
please enter your password: 3069
usercode and password not recognised
Do you want to try again?(y/n):

我已经在数据库中输入了正确的用户代码和密码。 我希望你能帮助我

1 个答案:

答案 0 :(得分:0)

"SELECT * FROM `user` WHERE usercode ='$usercode' AND password = '$password'"将在数据库中搜索$usercode$password。您将需要替换这些值。

理想情况下,通过使用SQL绑定/参数化查询。

示例:

    usercode = input("please enter your usercode: ")
    password = input("please enter your password: ")

    sql = "SELECT * FROM `user` WHERE usercode = %s AND password = %s"
    cursor.execute(sql, (usercode, password))

更多示例可在PyMySQL github页面上找到:https://github.com/PyMySQL/PyMySQL


如果您不想使用绑定,也可以通过格式化自己来构建语句。

注意:在生产环境中,这是一种安全隐患,绑定是执行此操作的首选方法,下面的示例实际上只是为了显示替代方法。

    usercode = input("please enter your usercode: ")
    password = input("please enter your password: ")

    sql = "SELECT * FROM `user` WHERE usercode='{}' AND password='{}'".format(usercode, password)
    cursor.execute(sql)