写入MS Access表,python win32com [英] Write to MS Access table, python win32com

查看:68
本文介绍了写入MS Access表,python win32com的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在与win32com.client一起使用python,以尝试将行写入/插入到MS Access表中.我在此处.基本上,对我自己使用的代码进行了一些修改:

I'm playing around with win32com.client for python to try to write/insert a row to a MS Access table. I've found an example of how to connect and query an Access table here. Basically, their code slightly modified for my own use is:

import win32com.client

connection = win32com.client.Dispatch(r'ADODB.Connection')
DSN = 'PROVIDER=Microsoft.Jet.OLEDB.4.0;DATA SOURCE=c:\\testdb.mdb;'
connection.Open(DSN)
recordset = win32com.client.Dispatch(r'ADODB.Recordset')
recordset.Open('SELECT * FROM Table1', connection, 1, 3)
fields_dict = {}
for x in range(recordset.Fields.Count):
    fields_dict[x] = recordset.Fields.Item(x).Name
    print fields_dict[x], recordset.Fields.Item(x).Value

因此,这告诉我如何在Access表上执行select语句.我希望能够将行和数据写入表中.当将win32com用于MS Office产品时,我倾向于进入 MSDN页面并尝试将VBA代码解释为python代码,但这使我有些手铐.加上长时间搜索后在互联网上找不到任何示例,这使我再次猜测这是否可行?希望外面有人曾经玩过这个游戏并提出了建议.

So this tells me how to execute a select statement on the Access table. I'd like to be able to write rows and data to the table. When using win32com for MS Office products, I tend to dive into the MSDN pages and try to interpret the VBA code for python code, but this one has me a bit handcuffed. Couple that with no examples found on the internet after lengthy searches has made me second guess whether or not this is possible? hopefully someone out there has played with this before and has a suggestion.

推荐答案

正如我在对该问题的评论中提到的那样,使用pyodbc(或pypyodbc)和Access ODBC驱动程序是执行CRUD操作的更常见方法,但是如果您真的想使用win32com和OLEDB,那么您可以像这样进行 UPDATE :

As I mentioned in my comment to the question, using pyodbc (or pypyodbc) and the Access ODBC driver is a more common way of doing CRUD operations, but if you really want to use win32com and OLEDB then you could do an UPDATE like this:

import win32com.client

# ADODB constants
adVarWChar = 202
adInteger = 3
adParamInput = 1

connection = win32com.client.Dispatch(r'ADODB.Connection')
DSN = (
    r'PROVIDER=Microsoft.Jet.OLEDB.4.0;'
    r'DATA SOURCE=C:\Users\Public\mdbTest.mdb;'
    )
connection.Open(DSN)
cmd = win32com.client.Dispatch(r'ADODB.Command')
cmd.ActiveConnection = connection
cmd.CommandText = "UPDATE Donors SET LastName = ? WHERE ID = ?"
cmd.Parameters.Append(cmd.CreateParameter("?", adVarWChar, adParamInput, 255))
cmd.Parameters.Append(cmd.CreateParameter("?", adInteger, adParamInput))
cmd.Parameters(0).Value = "Thompson"
cmd.Parameters(1).Value = 10
cmd.Execute()
connection.Close()

这篇关于写入MS Access表,python win32com的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆