从 Python 追加到 Access 的 SQL 查询

Posted

技术标签:

【中文标题】从 Python 追加到 Access 的 SQL 查询【英文标题】:SQL Query appending from Python to Access 【发布时间】:2019-02-07 20:34:47 【问题描述】:

我正在尝试将 Excel 文件读入 Python pandas 数据框,然后将该数据框附加到预先存在的 Access 数据库中。

我收到以下错误:

错误('HYC00', '[HYC00] [Microsoft][ODBC Microsoft Access Driver]可选功能未实现 (106) (SQLBindParameter)')

我已经读到这个错误通常是 pyodbc 4.0.25 的结果。我已将我的版本降级到 pyodbc 4.0.24,但仍然收到错误消息。

import glob
import os
import pandas as pd
import time
import pyodbc

# specify the folder that the files are sitting in 
list_of_files = glob.glob(r'C:\Users\CraigG\Test\*xlsx') 

# define the newest file in the folder
filename = min(list_of_files, key=os.path.getmtime)

# put excel file in data frame
df = pd.read_excel(filename)

print(pyodbc.version)

conn = pyodbc.connect(r'DRIVER=Microsoft Access Driver (*.mdb, *.accdb);' +
                      r'DBQ=C:\\Users\\CraigG\\Test\\Db\\Master.accdb;')
cursor = conn.cursor()

for index, row in df.iterrows():

   AccountNum = row["Account #"]
   CustomerNum = row["Customer #"]
   CustomerName = row["Customer Name"]
   AccountName = row["Account Name"]
   SalesRegisterNum = row["Sales Register #"]
   InvoiceDate = row["Invoice Date"]
   BillingMonthDate = row["BillingMonthDate"]
   WrittenBy = row["Written By"]
   Mfr = row["Mfr"]
   CatalogNo = row["CatalogNo"]
   LineType = row["LineType"]
   UPC = row["UPC"]
   QTYShip = row["QTY Ship"] 
   Price = row["Price"]
   PriceUOM = row["Price UOM"]
   ExtenedPrice = row["Extened Price"]
   Cost = row["Cost"]
   CostUOM = row["Cost UOM"]
   ExtendedCost = row["Extended Cost"] 
   SPACost = row["SPA Cost"]
   SPACostUOM = row["SPA Cost UOM"]
   ExtendedSPACost = row["Extended SPA Cost"]
   PCNum = row["PC #"]

   sql = "INSERT INTO Master ([Account #], [Customer #], [Customer Name], [Account Name], [Sales Register #], [Invoice Date], [BillingMonthDate], [Written By], [Mfr], [CatalogNo], [LineType], [UPC], [QTY Ship], [Price], [Price UOM], [Extened Price], [Cost], [Cost UOM], [Extended Cost], [SPA Cost], [SPA Cost UOM], [Extended SPA Cost], [PC #]) VALUES(?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)"

   params = (AccountNum, CustomerNum, CustomerName, AccountName, 
             SalesRegisterNum, InvoiceDate, BillingMonthDate, WrittenBy, Mfr, 
             CatalogNo, LineType, UPC, QTYShip, Price, PriceUOM, ExtenedPrice, Cost, 
             CostUOM, ExtendedCost, SPACost, SPACostUOM, ExtendedSPACost, PCNum)

   cursor.execute(sql, params)
   cursor.commit()

【问题讨论】:

您的 DataFrame 是否包含最初可能是字符串的值(例如“Account #”、“Customer #”),但在 DataFrame 中以大于 2147483647 的整数形式结束?如果是这样,那么 pyodbc 将尝试将它们作为 BIGINT(64 位签名)传递给 Access ODBC 驱动程序,但驱动程序不会接受它们。 整数最大值为6位 【参考方案1】:

不需要熊猫作为媒介。离开图书馆学习数据科学! MS Access 与它的兄弟 MS Excel 配合得很好。只需在工作簿中查询没有任何循环的纯 SQL 调用。

以下假设 Excel 数据与在名为 Sheet1 的工作表中的单元格 A1 开始的 Access 表保持相同的列名。根据需要调整FROM 子句。

import glob
import os
import pyodbc

# specify the folder that the files are sitting in 
list_of_files = glob.glob(r'C:\Users\CraigG\Test\*xlsx') 

# define the newest file in the folder
filename = min(list_of_files, key=os.path.getmtime)

sql = r"""INSERT INTO Master ([Account #], [Customer #], [Customer Name], [Account Name], [Sales Register #], 
                              [Invoice Date], [BillingMonthDate], [Written By], [Mfr], [CatalogNo], [LineType], 
                              [UPC], [QTY Ship], [Price], [Price UOM], [Extened Price], [Cost], [Cost UOM], 
                              [Extended Cost], [SPA Cost], [SPA Cost UOM], [Extended SPA Cost], [PC #]) 
          SELECT e.[Account #], e.[Customer #], e.[Customer Name], e.[Account Name], e.[Sales Register #], 
                 e.[Invoice Date], e.[BillingMonthDate], e.[Written By], e.[Mfr], e.[CatalogNo], e.[LineType], 
                 e.[UPC], e.[QTY Ship], e.[Price], e.[Price UOM], e.[Extened Price], e.[Cost], e.[Cost UOM], 
                 e.[Extended Cost], e.[SPA Cost], e.[SPA Cost UOM], e.[Extended SPA Cost], e.[PC #]

          FROM [Excel 12.0 Xml;HDR=Yes;Database=xl].[Sheet1$] AS e;
       """.format(xl=filename)

conn = pyodbc.connect(r'DRIVER=Microsoft Access Driver (*.mdb, *.accdb);' +
                      r'DBQ=C:\Users\CraigG\Test\Db\Master.accdb;')    
cursor = conn.cursor()

cursor.execute(sql)
cursor.commit()

cursor.close()
conn.close()

【讨论】:

很高兴听到并乐于提供帮助!

以上是关于从 Python 追加到 Access 的 SQL 查询的主要内容,如果未能解决你的问题,请参考以下文章

Access (VBA) - 追加表中尚未包含的记录

在Access 2010中运行追加查询时出现“表已存在”错误

使用 Python/pyodbc 插入 Access DB

Microsoft Access 无法在追加查询中追加所有记录

将每月数据从 Excel 上传到 Access

如何对一个字段追加内容。SQL语句怎么实现