2012-06-25 86 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

相關問題