2013-05-07 60 views
1

你能做這樣的事嗎?我有以下但cursor.execute不喜歡selectSQL的語法。最終,我正在遍歷.accdb中的所有表,並將每個表中的記錄插入另一個具有相同表和字段的.accdb。原因在於,從Tablet PC上的現場數據收集中引入新記錄以在服務器上掌握數據庫。在循環內生成pyodbc SQL語法

import pyodbc 

connOtherDB = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='path to my dbase;") 
otherDBtbls = connOtherDB.cursor().tables() 
for t in otherDBtbls: 
    if t.table_name.startswith("tbl"): #ignores MS sys tables 
     cursor = connOtherDB.cursor() 
     #selectSQL = '"SELECT * from '+ str(t.table_name) + '"' 
     cursor.execute("SELECT * from tblDatabaseComments") #this works if I refer to a table by name 
     cursor.execute(selectSQL) #this does not work. throws SQL syntax error 
     row = cursor.fetchone() 
     if row: 
      print t.table_name 
      print row 

回答

1

使用str.format(),以緩解SQL語句的建設:

import pyodbc 

connOtherDB = pyodbc.connect("Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ='path to my dbase;") 
otherDBtbls = connOtherDB.cursor().tables() 
for t in otherDBtbls: 
    if t.table_name.startswith("tbl"): #ignores MS sys tables 
     cursor = connOtherDB.cursor() 
     selectSQL = 'SELECT * FROM {}'.format(t.table_name) 
     cursor.execute(selectSQL) 
     row = cursor.fetchone() 
     if row: 
      print t.table_name 
      print row 

順便說一句,承擔對行的最大長度和可變命名指導看起來PEP 8 -- Style Guide for Python Code,其他編碼約定中。

+0

謝謝beargle。像魅力一樣工作。如果風格沒有讓我離開,我是一個蟒蛇新手;-)。欣賞風格指南鏈接。我會仔細研究並嘗試改進。我介紹的一個介紹告訴我們使用lowerCamelCase,但我想我甚至沒有正確實現它。 – dgj32784 2013-05-08 03:43:05

+0

@ dgj32784很高興聽到它的幫助。如果答案是有用的並記住你的問題,請記住加入並接受。 – Bryan 2013-05-08 11:59:46