我試圖從一個數據庫中讀取數據,然後在另一臺機器上寫入另一個數據。我得到一個TypeError: not all arguments converted during string formatting
Pyodbc&SQL Server-TypeError:並非在字符串格式化過程中轉換的所有參數
這裏是我的代碼:
import pyodbc
#read from db
read_db = pyodbc.connect(driver='{SQL Server}', host='hostname', databse='DBa', user='user', password='pwd')
cur = read_db.cursor()
cur.execute("SELECT * FROM origin_table")
#write to db
write_db = pyodbc.connect(driver='{SQL Server}', host='hostname', databse='DBb', user='user', password='pwd')
#get rows from read
rows = cur.fetchall()
#make list, init
read_list = []
i=0
#add row, write
for row in rows:
read_list.append(row)
params = ['%s' for item in read_list]
sql = "INSERT INTO destination_table (col1, col2, col3, col4, col5, col6, col7) VALUES (%%s,%%s,%%s,%%s,%%s,%%s,%%s);" % ','.join(params)
cur2 = write_db.cursor()
cur2.execute(sql, params)
這裏是從讀輸出的樣子:
('Fname', 'Lname', u'THIS', 'THAT', Decimal('0'), datetime.datetime(2015, 6, 20, 3, 26, 47), u'THE OTHER')
我已經嘗試了很多不同的解決方案,我已經發現並得到只有TypeError:
是我看起來最接近。 我是否需要做某種明確的類型轉換/規範?
當我三聯引用SQL並取出逃生%
,像這樣:
"""INSERT INTO destination_table (col1, col2, col3, col4, col5, col6, col7) VALUES (%s,%s,%s,%s,%s,%s,%s);""" % ','.join(params)
我得到的錯誤是TypeError: not enough arguments for format string
更新時間: 改變了','.join(params)
到tuple(params)
(如建議下面),我仍然得到一個TypeError: not enough arguments for format string
對於SQLite3的行爲是值得的不同;如果「In」數據庫是Sqlite,那麼'rows = cur1.fetchall()'返回一個'sqlite3.Row'對象列表。你必須這樣訪問它們: 'cur2.execute(sql,list(read_list [i]))'' –