2015-10-15 88 views
1

我工作的這一段代碼,蟒蛇2.6.6,舊版本,因爲我將與執行Linux服務器上運行此腳本(可能是CentOS 6的,或Debian的)基礎知識庫(穩定)已安裝,並且沒有權限安裝不在這些回購版上的軟件。類型錯誤:「快譯通」對象不支持索引

這剪斷照顧到從數據庫(MySQL的)以一定的模式(分貝結構)選擇數據,並且在其他數據庫(PostgreSQL的)配有一個不同的模式插入。

cur_msql.execute("SELECT customerName, contactName, address, city, postal_code, country FROM tablename") 

args_str = ','.join(cur_psql.mogrify("(%s,%s,%s,%s,%s,%s)", x) for x in cur_msql) 

try: 
    cur_psql.execute("INSERT INTO tablename (name, contact, address, city, cap, country) \ 
        VALUES " + args_str) 
except psycopg2.Error as e: 
    print "Cannot execute that query", e.pgerror 
    sys.exit("Leaving early the script") 

我得到這個錯誤:

TypeError: 'dict' object does not support indexing 

以下職位沒有固定我的問題:

official website of psycopg2我發現這一點,但我有認識上的不好的時候是什麼意思:

Psycopg always require positional arguments to be passed as a sequence, even when the query takes a single parameter. And remember that to make a single item tuple in Python you need a comma! See Passing parameters to SQL queries.

我認爲我的問題是有關to this


+0

是cur_msql和cur_psql引用相同的db或不同的dbs?如果它們彼此可訪問,則可以發出INSERT .. SELECT查詢https://dev.mysql.com/doc/refman/5.1/en/insert-select.html – Caleth

+0

它們引用不同的數據庫,源數據庫是mysql,postgres中的目標數據庫。這是一個將數據從一個數據庫遷移到另一個數據庫的腳本。兩個數據庫上的模式(db結構)是不同的。謝謝你的回覆:) – lese

回答

1

cur_psql.mogrify需要位置參數時你用它這樣的,但是你可以使用named parameters(%(customerName)s,%(contactName)s,%(address)s,%(city)s,%(postal_code)s,%(country)s)

雖這麼說,而不必蟒蛇做參數的巨大字符串,而是考慮使用cur_psql.executemany

cur_psql.executemany("INSERT INTO tablename (name, contact, address, city, cap, country) VALUES (%(customerName)s,%(contactName)s,%(address)s,%(city)s,%(postal_code)s,%(country)s)", cur_msql) 
+0

謝謝你的回答,我正在分析它。我已經考慮了executemany方法,但是我放棄了它,因爲它已經結束了性能的消失,因爲這種方法分別執行了很多插入操作,而我嘗試的方法將執行一次全部插入操作記錄。 [在這裏他們談](100%更多速度)(http://stackoverflow.com/questions/8134602/psycopg2-insert-multiple-rows-with-one-query/10147451#10147451)。我的腳本將不得不處理可觀的數據集 – lese

+0

謝謝,你的第一個提示修復了我的問題:) – lese

相關問題