【问题标题】:SQL TypeError: can't concat tuple to bytesSQL TypeError:无法将元组连接到字节
【发布时间】:2017-12-24 10:25:54
【问题描述】:

运行这段代码会返回“无法将元组连接到字节”的类型错误,但在我的代码中,我看不到字节来自哪里,因此不确定如何修复我的代码。哪一行代码是以字节的形式有指针吗?

def array2python():

     mfcc = "US"
     number = 8 #could be any number from 0 to 9
     t = (number, mfcc)
     conn = pymysql.connect( host=hostname, port = port, user=username, passwd=password, db=database, charset='utf8mb4', cursorclass=pymysql.cursors.DictCursor )
     cur = conn.cursor()
     query = ('INSERT INTO audioFiles VALUES (?,?)', t)
     cur.execute(query)
     conn.close()

【问题讨论】:

    标签: python mysql


    【解决方案1】:

    问题出在这一行:

    query = ('INSERT INTO audioFiles VALUES (?,?)', t)
    

    query 定义为一个元组,然后execute() 无法理解。

    你的意思是:

    query = 'INSERT INTO audioFiles VALUES (?,?)'
    cur.execute(query, t)
    

    而且,我认为你需要使用%s as a placeholder

    query = 'INSERT INTO audioFiles VALUES (%s,%s)'
    cur.execute(query, t)
    

    【讨论】:

    • 我怀疑我需要做 %s 但这会导致 SQL 注入吗?
    • @jc76 如果您使用这些 %s 占位符进行字符串格式化 - 那么,是的。但是,在我们的例子中,我们将它们用作查询占位符并将第二个参数中的参数传递给execute()。谢谢。
    猜你喜欢
    • 1970-01-01
    • 2020-03-10
    • 2018-05-02
    • 1970-01-01
    • 2019-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多