无法获取正确的插入语句用于我的Access数据库。

huangapple go评论92阅读模式
英文:

Fail to get the correct insert statment for my Access database

问题

我想要从我的Excel文件导入数据到我的Access数据库中的多个表格。我已经将要导入的数据从我的xlsx文件映射到了Access数据表中的列名,但不知何故插入语句总是出错。你能帮助我吗?

#导入必要的模块
import pandas as pd
import pyodbc

# ODBC连接
connection_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\ArtiPro.accdb;'
conn = pyodbc.connect(connection_string)

def import_excel_to_access(excel_file_path, table_mappings):
    # 将Excel文件读取到pandas DataFrame中
    df = pd.read_excel(r'C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\A001.xlsx')

    # 创建游标以执行SQL查询
    cursor = conn.cursor()

    for table_name, column_mapping in table_mappings.items():
        

          # 准备带有选定列的INSERT查询
        insert_query = f"INSERT INTO {table_name} ({', '.join(column_mapping.values())}) VALUES ({', '.join(['?' for _ in column_mapping.values()])})"
        print(insert_query)
        # 将数据插入Access表格
        for row in df.rename(columns=column_mapping)[column_mapping.values()].itertuples(index=False):
            cursor.execute(insert_query, row)

        print(insert_query)
    # 提交更改并关闭连接
    conn.commit()
    conn.close()

if __name__ == '__main__':
    excel_file_path = r'C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\A001.xlsx'
    table_mappings = {
        '01_Basic Data': {
            'SID': 'SID',
            '1': 'AD intake',
            '2a': 'AD trade name',
            '2b': 'AD substance',
            '3a': 'Drug Dose (in mg)',
            '3b': 'Drug Rhythm',
            '4': 'Age',
            '5': 'Gender',
            '6': 'Ethnicity'
   
        },
        '02_Medication Effect': {
            'SID': 'SID',
            '7': 'Q7',
            '8': 'Q8',
            '8a': 'Q8a',
            '9': 'Q9',
            '9a': 'Q9a',
            '10': 'Q10',
            '10a': 'Q10a',
            '11': 'Q11',
            '11a': 'Q11a',
            '12': 'Q12',
            '12a': 'Q12a',
            '13': 'Q13',
            '13a': 'Q13a',
            '14': 'Q14',
            '14a': 'Q14a',
            '15': 'Q15',
            '16': 'Q16',

            
        },
        
        '03_ADRs': {
            'SID': 'SID',
            'NW_frei': 'ADRs (free speech)',
            '17': 'Q17_dry mouth',
            '17a': 'Q17a_dry mouth',
            '17b': 'Q17b_dry mouth',
            '17c': 'Q17c_dry mouth',
            '17d': 'Q17d_dry mouth',
            '17e': 'Q17e_dry mouth',
            '18': 'Q18_blurred vision',
            '18a': 'Q18a_blurred vision',
            '18b': 'Q18b_blurred vision',
            '18c': 'Q18c_blurred vision',
            '18d': 'Q18d_blurred vision',
            '18e': 'Q18e_blurred vision',
            '19': 'Q19_dizziness',
            '19a': 'Q19a_dizziness',
            '19b': 'Q19b_dizziness',
            '19c': 'Q19c_dizziness',
            '19d': 'Q19d_dizziness',
            '19e': 'Q19e_dizziness',
            '20': 'Q20_fall',
            '20a': 'Q20a_fall',
            '20b': 'Q20b_fall',
            '20c': 'Q20c_fall',
            '20d': 'Q20d_fall',
            '20e': 'Q20e_fall',
            '21': 'Q21_increased appetite',
            '21a': 'Q21a_increased appetite',
            '21b': 'Q21b_increased appetite',
            '21c': 'Q21c_increased appetite',
            '21d': 'Q21d_increased appetite',
            '21e': 'Q21e_increased appetite',
            '22': 'Q22_reduced appetite',
            '22a': 'Q22a_reduced appetite',           
            '22b': 'Q22b_reduced appetite',
            '22c': 'Q22c_reduced appetite',
            '22d': 'Q22d_reduced appetite',
            '22e': 'Q22e_reduced appetite',
            '23': 'Q23_weight gain',
            '23a': 'Q23a_weight gain',
            '23b': 'Q23b_weight gain',
            '23c': 'Q23c_weight gain',
            '23d': 'Q23d_weight gain',
            '23e': 'Q23e_weight gain',
            '24': 'Q24_weight loss',
            '24a': 'Q24a_weight loss',
            '24b': 'Q24b_weight loss',
            '24c': 'Q24c_weight loss',
            '24d': 'Q24d_weight loss',
            '24e': 'Q24e_weight loss',           
            '25': 'Q25_nausea',
            '25a': 'Q25a_nausea',
            '25b': 'Q25b_nausea',
            '25c': 'Q25c_nausea',
            '25d': 'Q25d_nausea',
            '25e': 'Q25e_nausea',
            '26': 'Q26_vomiting',
            '26a': 'Q26a_vomiting',
            '26b': 'Q26b_vomiting',
            '26c': 'Q26c_vomiting',
            '26d': 'Q26d_vomiting',
            '26e': 'Q26e_vomiting',
            '27': 'Q27_bleeding',
            '27a': 'Q27a_bleeding',
            '27aa1': 'Q27aa1_bleeding',
            '27aa2': 'Q27aa2_bleeding',
            '27aa3': 'Q27aa3_bleeding',
            '27aa4': 'Q27aa4_bleeding',
            '

<details>
<summary>英文:</summary>

I want to import data from my Excel file to several tables in my access database. I already mapped all data I wanted to import from my xlsx.file to the column names in the access data tables, but somehow fail to get the insert statement right. Could you help me?

#import necessary modules
import pandas as pd
import pyodbc

ODBC connection

connection_string = r'DRIVER={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\ArtiPro.accdb;'
conn = pyodbc.connect(connection_string)

def import_excel_to_access(excel_file_path, table_mappings):
# Read the Excel file into a pandas DataFrame
df = pd.read_excel(r'C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\A001.xlsx')

# Create a cursor to execute SQL queries
cursor = conn.cursor()
for table_name, column_mapping in table_mappings.items():
# Prepare the INSERT query with selected columns
insert_query = f&quot;INSERT INTO table_name ({&#39;, &#39;.join(column_mapping.values())}) VALUES ({&#39;, &#39;.join([&#39;?&#39; for _ in column_mapping.values()])})&quot;
print(insert_query)
# Insert data into the Access table
for row in df.rename(columns=column_mapping)[column_mapping.values()].itertuples(index=False):
cursor.execute(insert_query, row)
print(insert_query)
# Commit the changes and close the connection
conn.commit()
conn.close()

if name == 'main':
excel_file_path = r'C:\Users\User\Downloads\OneDrive_2023-07-24\Fragebogen Rohdaten\A001.xlsx'
table_mappings = {
'01_Basic Data': {
'SID': 'SID',
'1': 'AD intake',
'2a': 'AD trade name',
'2b': 'AD substance',
'3a': 'Drug Dose (in mg)',
'3b': 'Drug Rhythm',
'4': 'Age',
'5': 'Gender',
'6': 'Ethnicity'

    },
&#39;02_Medication Effect&#39;: {
&#39;SID&#39;: &#39;SID&#39;,
&#39;7&#39;: &#39;Q7&#39;,
&#39;8&#39;: &#39;Q8&#39;,
&#39;8a&#39;: &#39;Q8a&#39;,
&#39;9&#39;: &#39;Q9&#39;,
&#39;9a&#39;: &#39;Q9a&#39;,
&#39;10&#39;: &#39;Q10&#39;,
&#39;10a&#39;: &#39;Q10a&#39;,
&#39;11&#39;: &#39;Q11&#39;,
&#39;11a&#39;: &#39;Q11a&#39;,
&#39;12&#39;: &#39;Q12&#39;,
&#39;12a&#39;: &#39;Q12a&#39;,
&#39;13&#39;: &#39;Q13&#39;,
&#39;13a&#39;: &#39;Q13a&#39;,
&#39;14&#39;: &#39;Q14&#39;,
&#39;14a&#39;: &#39;Q14a&#39;,
&#39;15&#39;: &#39;Q15&#39;,
&#39;16&#39;: &#39;Q16&#39;,
},
&#39;03_ADRs&#39;: {
&#39;SID&#39;: &#39;SID&#39;,
&#39;NW_frei&#39;: &#39;ADRs (free speech)&#39;,
&#39;17&#39;: &#39;Q17_dry mouth&#39;,
&#39;17a&#39;: &#39;Q17a_dry mouth&#39;,
&#39;17b&#39;: &#39;Q17b_dry mouth&#39;,
&#39;17c&#39;: &#39;Q17c_dry mouth&#39;,
&#39;17d&#39;: &#39;Q17d_dry mouth&#39;,
&#39;17e&#39;: &#39;Q17e_dry mouth&#39;,
&#39;18&#39;: &#39;Q18_blurred vision&#39;,
&#39;18a&#39;: &#39;Q18a_blurred vision&#39;,
&#39;18b&#39;: &#39;Q18b_blurred vision&#39;,
&#39;18c&#39;: &#39;Q18c_blurred vision&#39;,
&#39;18d&#39;: &#39;Q18d_blurred vision&#39;,
&#39;18e&#39;: &#39;Q18e_blurred vision&#39;,
&#39;19&#39;: &#39;Q19_dizziness&#39;,
&#39;19a&#39;: &#39;Q19a_dizziness&#39;,
&#39;19b&#39;: &#39;Q19b_dizziness&#39;,
&#39;19c&#39;: &#39;Q19c_dizziness&#39;,
&#39;19d&#39;: &#39;Q19d_dizziness&#39;,
&#39;19e&#39;: &#39;Q19e_dizziness&#39;,
&#39;20&#39;: &#39;Q20_fall&#39;,
&#39;20a&#39;: &#39;Q20a_fall&#39;,
&#39;20b&#39;: &#39;Q20b_fall&#39;,
&#39;20c&#39;: &#39;Q20c_fall&#39;,
&#39;20d&#39;: &#39;Q20d_fall&#39;,
&#39;20e&#39;: &#39;Q20e_fall&#39;,
&#39;21&#39;: &#39;Q21_increased appetite&#39;,
&#39;21a&#39;: &#39;Q21a_increased appetite&#39;,
&#39;21b&#39;: &#39;Q21b_increased appetite&#39;,
&#39;21c&#39;: &#39;Q21c_increased appetite&#39;,
&#39;21d&#39;: &#39;Q21d_increased appetite&#39;,
&#39;21e&#39;: &#39;Q21e_increased appetite&#39;,
&#39;22&#39;: &#39;Q22_reduced appetite&#39;,
&#39;22a&#39;: &#39;Q22a_reduced appetite&#39;,           
&#39;22b&#39;: &#39;Q22b_reduced appetite&#39;,
&#39;22c&#39;: &#39;Q22c_reduced appetite&#39;,
&#39;22d&#39;: &#39;Q22d_reduced appetite&#39;,
&#39;22e&#39;: &#39;Q22e_reduced appetite&#39;,
&#39;23&#39;: &#39;Q23_weight gain&#39;,
&#39;23a&#39;: &#39;Q23a_weight gain&#39;,
&#39;23b&#39;: &#39;Q23b_weight gain&#39;,
&#39;23c&#39;: &#39;Q23c_weight gain&#39;,
&#39;23d&#39;: &#39;Q23d_weight gain&#39;,
&#39;23e&#39;: &#39;Q23e_weight gain&#39;,
&#39;24&#39;: &#39;Q24_weight loss&#39;,
&#39;24a&#39;: &#39;Q24a_weight loss&#39;,
&#39;24b&#39;: &#39;Q24b_weight loss&#39;,
&#39;24c&#39;: &#39;Q24c_weight loss&#39;,
&#39;24d&#39;: &#39;Q24d_weight loss&#39;,
&#39;24e&#39;: &#39;Q24e_weight loss&#39;,           
&#39;25&#39;: &#39;Q25_nausea&#39;,
&#39;25a&#39;: &#39;Q25a_nausea&#39;,
&#39;25b&#39;: &#39;Q25b_nausea&#39;,
&#39;25c&#39;: &#39;Q25c_nausea&#39;,
&#39;25d&#39;: &#39;Q25d_nausea&#39;,
&#39;25e&#39;: &#39;Q25e_nausea&#39;,
&#39;26&#39;: &#39;Q26_vomiting&#39;,
&#39;26a&#39;: &#39;Q26a_vomiting&#39;,
&#39;26b&#39;: &#39;Q26b_vomiting&#39;,
&#39;26c&#39;: &#39;Q26c_vomiting&#39;,
&#39;26d&#39;: &#39;Q26d_vomiting&#39;,
&#39;26e&#39;: &#39;Q26e_vomiting&#39;,
&#39;27&#39;: &#39;Q27_bleeding&#39;,
&#39;27a&#39;: &#39;Q27a_bleeding&#39;,
&#39;27aa1&#39;: &#39;Q27aa1_bleeding&#39;,
&#39;27aa2&#39;: &#39;Q27aa2_bleeding&#39;,
&#39;27aa3&#39;: &#39;Q27aa3_bleeding&#39;,
&#39;27aa4&#39;: &#39;Q27aa4_bleeding&#39;,
&#39;27aa5&#39;: &#39;Q27aa5_bleeding&#39;,
&#39;27aa6&#39;: &#39;Q27aa6_bleeding&#39;,
&#39;27b&#39;: &#39;Q27b_bleeding&#39;,           
&#39;27c&#39;: &#39;Q27c_bleeding&#39;,
&#39;27d&#39;: &#39;Q27d_bleeding&#39;,
&#39;27e&#39;: &#39;Q27e_bleeding&#39;,
&#39;28&#39;: &#39;Q28_constipation&#39;,
&#39;28a&#39;: &#39;Q28a_constipation&#39;,
&#39;28b&#39;: &#39;Q28b_constipation&#39;,
&#39;28c&#39;: &#39;Q28c_constipation&#39;,
&#39;28d&#39;: &#39;Q28d_constipation&#39;,
&#39;28e&#39;: &#39;Q28e_constipation&#39;,
&#39;29&#39;: &#39;Q29_diarrhoea&#39;,
&#39;29a&#39;: &#39;Q29a_diarrhoea&#39;,
&#39;29b&#39;: &#39;Q29b_diarrhoea&#39;,
&#39;29c&#39;: &#39;Q29c_diarrhoea&#39;,
&#39;29d&#39;: &#39;Q29d_diarrhoea&#39;,
&#39;29e&#39;: &#39;Q29e_diarrhoea&#39;,
&#39;30&#39;: &#39;Q30_urinary incontinence&#39;,           
&#39;30a&#39;: &#39;Q30a_urinary incontinence&#39;,
&#39;30b&#39;: &#39;Q30b_urinary incontinence&#39;,
&#39;30c&#39;: &#39;Q30c_urinary incontinence&#39;,
&#39;30d&#39;: &#39;Q30d_urinary incontinence&#39;,
&#39;30e&#39;: &#39;Q30e_urinary incontinence&#39;,
&#39;31&#39;: &#39;Q31_urinary retention&#39;,
&#39;31a&#39;: &#39;Q31a_urinary retention&#39;,
&#39;31b&#39;: &#39;Q31b_urinary retention&#39;,
&#39;31c&#39;: &#39;Q31c_urinary retention&#39;,
&#39;31d&#39;: &#39;Q31d_urinary retention&#39;,
&#39;31e&#39;: &#39;Q31e_urinary retention&#39;,
&#39;33&#39;: &#39;Q33&#39;,
&#39;weitere NW_frei&#39;: &#39;Notes&#39;
}
}

import_excel_to_access(excel_file_path, table_mappings)


But somehow it fails me every time, tried a lot already

INSERT INTO table_name (SID, AD intake, AD trade name, AD substance, Drug Dose (in mg), Drug Rhythm, Age, Gender, Ethnicity) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)

ProgrammingError Traceback (most recent call last)
<ipython-input-24-68b37adef976> in <module>
174
175
--> 176 import_excel_to_access(excel_file_path, table_mappings)

<ipython-input-24-68b37adef976> in import_excel_to_access(excel_file_path, table_mappings)
22 # Insert data into the Access table
23 for row in df.rename(columns=column_mapping)[column_mapping.values()].itertuples(index=False):
---> 24 cursor.execute(insert_query, row)
25
26 print(insert_query)

ProgrammingError: ('42000', '[42000] [Microsoft][ODBC-Treiber für Microsoft Access] Syntaxfehler in der INSERT INTO-Anweisung. (-3502) (SQLExecDirectW)')


</details>
# 答案1
**得分**: 0
需要在某些字段名称周围加上*括号*:
```sql
INSERT INTO table_name (SID, [AD intake], [AD trade name], [AD substance], [Drug Dose (in mg)], [Drug Rhythm], Age, Gender, Ethnicity) ...
英文:

You need brackets around some field names:

INSERT INTO table_name (SID, [AD intake], [AD trade name], [AD substance], [Drug Dose (in mg)], [Drug Rhythm], Age, Gender, Ethnicity) ...

huangapple
  • 本文由 发表于 2023年7月24日 18:30:45
  • 转载请务必保留本文链接:https://go.coder-hub.com/76753590.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定