4
我想用我的計劃內的executemany存儲20條記錄一次,繼承人它在文檔中說...MySQLdb executemany使用列表作爲輸入?
c.executemany(
"""INSERT INTO breakfast (name, spam, eggs, sausage, price)
VALUES (%s, %s, %s, %s, %s)""",
[
("Spam and Sausage Lover's Plate", 5, 1, 8, 7.95),
("Not So Much Spam Plate", 3, 2, 0, 3.95),
("Don't Wany ANY SPAM! Plate", 0, 4, 3, 5.95)
])
不過,我在列表中有我的價值觀,而寧可不要做18個以上的版本,在我的列表中使用索引。
這裏是我的代碼如下...
db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [(str(keywords[0]), date, time, position[0])]
cursor.executemany(sql, params)
db.commit()
這工作得很好,並且它會犯的第一個關鍵字列表,與日期,時間和位置一起,我不希望有重複PARAMS 19次象下面...
db = connect_to_db()
cursor = db.cursor()
sql = "INSERT INTO gkey (keyword, date, time, position) VALUES (%s, %s, %s, %s)"
params = [
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
(str(keywords[0]), date, time, position[0])
]
cursor.executemany(sql, params)
db.commit()
上面的什麼,我想避免一個例子(索引需要遞增它的工作,我知道!;))
我得到一個錯誤當我嘗試將整個列表作爲一個值傳遞時,我需要一次一個地傳遞它們,有什麼想法?可以執行很多操作,還是應該循環更新一次?但我敢肯定,我嘗試過,並有類似的錯誤?雖然我沒有注意到它。
非常感謝!所以你可以在定義一個變量時循環?我認爲這將有其他應用程序傳遞給函數等參數? – jjjjj 2012-04-16 19:32:10
這是一個列表理解http://www.diveintopython.net/native_data_types/mapping_lists.html – vartec 2012-04-16 19:34:59
感謝您的鏈接 – jjjjj 2012-04-16 19:36:34