【问题标题】:Getting TypeError when inserting data to database将数据插入数据库时​​出现 TypeError
【发布时间】:2012-06-25 13:49:42
【问题描述】:

首先我从一个大学网站以元组元组的形式提取了一个大学列表:

(('name1', 'address1'), ('name2', 'address2'), ('name3', 'address3'))

然后我想在名为“sample”的数据库和表“collegelist”中编写它。表有两个字段(name varchar(400) not null,address varchar(500)):

代码如下:

for college in tuples:
   cursor.execute('INSERT INTO collegelist (name, address) VALUES ("%s", "%s")') %(college[0], college[1])
   db.commit()
db.close()

但它总是给出以下类型错误:

TypeError: unsupported operand type(s) for %: 'long' and 'tuple'

我也尝试只插入姓名和留下地址,然后我得到以下类型错误:

TypeError: unsupported operand type(s) for %: 'long' and 'str'

现在我不明白“长”类型是从哪里来的。程序中只有字符串和元组。

注意:院校名称和地址有单引号、双引号、破折号、句号。

为什么会出现这个错误,我该如何消除它?提前致谢。

【问题讨论】:

    标签: python mysql typeerror


    【解决方案1】:

    cursor.execute('INSERT INTO collegelist (name, address) VALUES ("%s", "%s")') <--

    此时,您已关闭对execute 的呼叫。此外,您应该将参数传递给 execute,并且永远不要将它们解析到查询中。

    q_insert = "INSERT INTO collegelist (name,address) VALUES (%s,%s)"
    for college in tuples:
        cursor.execute(q_insert,(college[0], college[1]))
        db.commit()
    

    【讨论】:

    • 将参数值传递给 execute() 有助于防止SQL injection attacks,因为转义字符被解释为值的一部分,并且不会影响所涉及的查询。
    猜你喜欢
    • 2020-11-01
    • 1970-01-01
    • 2018-01-04
    • 1970-01-01
    • 1970-01-01
    • 2020-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多