简体   繁体   English

mysql使用python错误和SQL语法登录

[英]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 :) 我试图在连接到sql server的python中创建登录脚本,并检查用户输入以查看它是否与sql server匹配,以及是否确实登录了该帐户,但是我在脚本的sql端收到语法错误:)

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. 您的用户名未与AND运算符分开。 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. 并在来自用户输入并进入SQL查询的每个字符串上使用mysql_escape *函数。

  • I'm not sure if the escape syntax ( \\' )is correct for python, it would work for C, PHP and others... 我不确定转义语法(\\')是否适用于python,它是否适用于C,PHP和其他...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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