2 回答
TA贡献1813条经验 获得超2个赞
我猜你只需要正确格式化字符串即可成为有效的 SQL 查询。尝试这样的事情
sql = f"INSERT INTO table([Case2], [Last], ...) VALUES ({a2.value}, {b2.value}, ...)"
或者
sql = ''.join(test)
TA贡献1833条经验 获得超4个赞
这是工作代码!
import pyodbc
import openpyxl
path = ('C:\\Users\\Db_Mngr\\Desktop\\PythonTests\\Microsoft Studio Projects\\Access_Test.xlsx') #Set the path to the Excel document that you want to transfer data from
wb = openpyxl.load_workbook(path)
sheet = wb.active
b2 = sheet['B2']
c2 = sheet['C2']
d2 = sheet['D2']
e2 = sheet['E2']
f2 = sheet['F2']
g2 = sheet['G2']
h2 = sheet['H2']
i2 = sheet['I2']
j2 = sheet['J2']
k2 = sheet['K2']
l2 = sheet['L2']
m2 = sheet['M2']
n2 = sheet['N2']
o2 = sheet['O2']
#This is the trouble spot. If you've ever worked with this stuff you know that the formatting has to be PERFECT. A single space out of place throws errors.
startcmmd = "'''INSERT INTO Python_Test([Case2], [Last], [First], [Initial Intake], [Intake], [Age], [Gender], [Ethnic], [Race], [DOB], [SSN], [Educ Lvl], [Marital])VALUES('{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}', '{}')'''".format(b2.value, c2.value, d2.value, e2.value, f2.value, g2.value, h2.value, i2.value, j2.value, k2.value, l2.value, m2.value, n2.value)
#Get connected to your Access document
driver = '{Microsoft Access Driver(*.mdb, *accdb)}'
filepath = 'C:\\Users\\Db_Mngr\\Desktop\\PythonTests\\Microsoft Studio Projects\\HUD Report-2001-Copy For Python.mdb'
myDataSources = pyodbc.dataSources()
access_driver = myDataSources['MS Access Database']
#set up your cursor
cnxn = pyodbc.connect(driver=access_driver, dbq=filepath, autocommit=True)
crsr = cnxn.cursor()
#Now execute! Don't forget to run this with eval!
crsr.execute(eval(startcmmd))
添加回答
举报