2016-04-26 127 views
0

我有我想上傳到數據庫中的元組列表。我想用這樣做一個查詢,這樣我就不必在每個元組解析時打開連接。通過Python將元組列表導入到Postgres中

我的元組列表示例如下(這個列表將會相當長): tuple_list = [(u'17',u'1',u'2',u'2'),(u '17',u'2',u'1',u'4')]

我想在postgres中寫一個查詢,它將採用這個tuple_list並通過列表工作來填充名爲'Predictions'在一個調用數據庫。

單個呼叫看起來是這樣的:

insert into 'Predictions' (userid, fixture_no, home_score, away_score) values (17, 1, 2, 2) 

我已經看着我的元組轉換爲一個XML文件,但不知道是否存在使用元組的列表只是Postgres裏這樣做的更好的辦法?

如果沒有,我設法生產出看起來像這樣的XML文件...

<root> 
    <User_Id/> 
    <Fix_No/> 
    <Home_Score/> 
    <Away_Score/> 
    <User_Id>17</User_Id> 
    <Fix_No>1</Fix_No> 
    <Home_Score>2</Home_Score> 
    <Away_Score>2</Away_Score> 
    <User_Id>17</User_Id> 
    <Fix_No>2</Fix_No> 
    <Home_Score>1</Home_Score> 
    <Away_Score>4</Away_Score> 
</root> 

我的主要目的是對我所有的預測發送到數據庫中的一個鏡頭,而不是讓無數個電話這將使我的Web應用程序運行速度變慢

任何想法或建議將是偉大的!

回答

1

您可以使用postgresql documentation的示例部分中描述的多行VALUES語法。這裏是一個python剪切,從你的問題tuple_list創建插入語句。

tuple_list = [(u'17',u'1', u'2', u'2'), (u'17',u'2', u'1', u'4')] 
a = ["("+", ".join(a)+")" for a in tuple_list] 
sql = "insert into 'Predictions' (userid, fixture_no, home_score, away_score) VALUES %s" % (",".join(a)) 
print(sql) 

# Insert into database (code from memory) 
args_str = ','.join(cursor.mogrify("%s", (x,)) for x in tuple_list) 
cursor.execute("INSERT INTO 'Predictions' (userid, fixture_no, home_score, away_score) VALUES "+args_str) 

輸出:

insert into 'Predictions' (userid, fixture_no, home_score, away_score) VALUES (17, 1, 2, 2),(17, 2, 1, 4) 
+0

我是新來的Pos​​tgres,這樣的評論是非常有幫助的。由於我的元組列表可能有5個元組,甚至50個元組,我怎麼能寫出一個適合我傳遞給它的元組數量的查詢? – LemusThelroy

+0

這是一個夢幻般的答案。謝謝。如果這個查詢位於我的Python代碼中,你認爲從SQL注入安全嗎?由於tuple_list來自Web應用程序的用戶輸入。 – LemusThelroy

+0

@LemusThelroy你應該確保所有插入的數據正確地逃脫。最好的方法是創建存儲過程。這個例子不是保存! – salomonderossi

相關問題