Python SQL查询的类型错误

问题描述 投票:0回答:1

我想从我的python程序中执行一条SQL语句。为此,我使用了MySQLdb库。这是我的代码:

def execute(sql_statement):
    db = MySQLdb.connect("<DatabaseIP>", "<DatabaseUserName>", "<DatabasePassword>", "<DatabaseName>")
    cursor = db.cursor()
    cursor.execute(sql_statement)
    data = cursor.fetchone()
    db.close()
    return data

def look_up_user_id(username, password):
    print(type(username))
    print(type(password))
    sql_statement = "SELECT ID FROM user WHERE name = '" + username + "' AND password = '" + password + "'"
    print(sql_statement)
    return Database.execute(sql_statement)

这是从请求中提取用户名和密码的方法,以及实际上调用数据库类方法的方法。

@app.route('/auth', methods=['GET'])
def log_in():
    return AuthenticationManager.log_in(request.authorization.username, request.authorization.password)
def log_in(username, password):
    return Database.execute(SQLStatementBuilder.look_up_user_id(username, password))[0]

当我执行print(look_up_user_id("me", "password"))时,一切都会按需要进行,并且我获得了用户ID。但是,当我在基本身份验证标头中使用用户名和密码向我的程序发送HTTP请求时,我得到

File "<PythonPath>\Python\Python38\Lib\site-packages\MySQLdb\cursors.py", line 208, in execute
   assert isinstance(query, (bytes, bytearray))
AssertionError 

这是引发错误的方法

    def execute(self, query, args=None):
        """Execute a query.

        query -- string, query to execute on server
        args -- optional sequence or mapping, parameters to use with query.

        Note: If args is a sequence, then %s must be used as the
        parameter placeholder in the query. If a mapping is used,
        %(key)s must be used as the placeholder.

        Returns integer represents rows affected, if any
        """
        while self.nextset():
            pass
        db = self._get_db()

        if isinstance(query, unicode):
            query = query.encode(db.encoding)

        if args is not None:
            if isinstance(args, dict):
                nargs = {}
                for key, item in args.items():
                    if isinstance(key, unicode):
                        key = key.encode(db.encoding)
                    nargs[key] = db.literal(item)
                args = nargs
            else:
                args = tuple(map(db.literal, args))
            try:
                query = query % args
            except TypeError as m:
                raise ProgrammingError(str(m))
        assert isinstance(query, (bytes, bytearray))
        res = self._query(query)
        return res

look_up_user_id方法中的两次print调用在两个测试用例中以及对于密码和名称都只返回<class 'str'>

感谢您的帮助!

编辑:添加了引发错误的方法

python database types database-connection assertion
1个回答
0
投票

问题是lookup_user_id返回的是Database.execute(sql_statement)的结果,而[[that

© www.soinside.com 2019 - 2024. All rights reserved.