简体   繁体   中英

mysql sign in with python error with SQL syntax

Im trying to make a sign in script in python that connects to a sql server and checks users input to see if it matches the sql server and if it does sign that account in but i getting a syntax error with my sql side of the script Thanks :)

import MySQLdb

db = MySQLdb.connect(host="localhost",    # your host, usually localhost
                     user="root",         # your username
                     passwd="",  # your password
                     db="login")        # name of the data base

# you must create a Cursor object. It will let
#  you execute all the queries you need
cur = db.cursor()

while (True):
    username = raw_input("Username: ")
    password = raw_input("Password: ")
    if(cur.execute("SELECT * FROM USERS WHERE username =" + username + "AND password =" + password)):
        db.commit()
        print ("Logged in!")
    else:
        db.commit()
        print ("Failed to authenticate!")

Your username is not separated from the AND operator. The string will become something like:

SELECT * FROM USERS WHERE username =johnAND password =1234

It is a very good idea to put quotes around username and password values:

if(cur.execute("SELECT * FROM USERS WHERE username = \'" + username + "\' AND password = \'" + password + "\'")):

and also to use mysql_escape* functions on every string that comes from a user input and goes to a SQL query.

  • I'm not sure if the escape syntax ( \\' )is correct for python, it would work for C, PHP and others...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM