2012-06-25 84 views
0

时,首先,我在元组的元组的形式提取院校的名单,从大学网站:获取类型错误插入数据到数据库

((“名称​​1”,“地址1”),(“名2”, 'address2'),('name3','address3'))

然后我想写在名为'sample'的数据库和表'collegelist'中。表有两个字段(名称VARCHAR(400)NOT NULL,地址为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' 

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

Note: Names and addresses of colleges have single quotes, double quotes, dash, period.

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

回答

1

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

在这一点上,你已经关闭调用execute。另外,您应该将参数传递给execute,永远不会将EVER解析为查询。

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

传递参数值来执行()有助于防止[SQL注入攻击(http://www.unixwiz.net/techtips/sql-injection.html),因为转义字符被解释为值的一部分,并且不能影响涉及的查询。 – invert

相关问题