gpt4 book ai didi

python - 通过 Python 使用 ADO 将数据插入 MS Access 数据库时出现问题

转载 作者:太空狗 更新时间:2023-10-30 00:08:42 26 4
gpt4 key购买 nike

[编辑 2:在下面的答案中提供更多信息和调试...]

我正在编写一个 python 脚本来将 MS Access 数据库导出到一系列文本文件中,以允许进行更有意义的版本控制(我知道 - 为什么是 Access?为什么我不使用现有的解决方案?我们只是说限制是't of a technical nature).

我已经通过 comtypes 库使用 ADO 和 ADOX 成功导出了数据库的全部内容和结构,但是我在重新导入数据时遇到了问题。

我将每个表的内容导出到一个文本文件中,每行都有一个列表,如下所示:

[-9, u'No reply']
[1, u'My home is as clean and comfortable as I want']
[2, u'My home could be more clean or comfortable than it is']
[3, u'My home is not at all clean or comfortable']

以及导入上述文件的函数:

import os
import sys
import datetime
import comtypes.client as client
from ADOconsts import *
from access_consts import *

class Db:
def create_table_contents(self, verbosity = 0):
conn = client.CreateObject("ADODB.Connection")
rs = client.CreateObject("ADODB.Recordset")
conn.ConnectionString = self.new_con_string
conn.Open()
for fname in os.listdir(self.file_path):
if fname.startswith("Table_"):
tname = fname[6:-4]
if verbosity > 0:
print "Filling table %s." % tname
conn.Execute("DELETE * FROM [%s];" % tname)
rs.Open("SELECT * FROM [%s];" % tname, conn,
adOpenDynamic, adLockOptimistic)
f = open(self.file_path + os.path.sep + fname, "r")
data = f.readline()
print repr(data)
while data != '':
data = eval(data.strip())
print data[0]
print rs.Fields.Count
rs.AddNew()
for i in range(rs.Fields.Count):
if verbosity > 1:
print "Into field %s (type %s) insert value %s." % (
rs.Fields[i].Name, str(rs.Fields[i].Type),
data[i])
rs.Fields[i].Value = data[i]
data = f.readline()
print repr(data)
rs.Update()
rs.Close()
conn.Close()

除了数字值(double 和 int)作为零插入外,一切正常。关于问题出在我的代码、eval、comtypes 还是 ADO 上的任何想法?

编辑:我已经解决了插入数字的问题 - 将它们转换为字符串 (!) 似乎解决了 double 和整数字段的问题。

但是,我现在有一个不同的问题,以前被上面的问题所掩盖:无论数据类型如何,每一行的第一个字段都被设置为 0...有什么想法吗?

最佳答案

并找到了答案。

    rs = client.CreateObject("ADODB.Recordset")

需要:

    rs = client.CreateObject("ADODB.Recordset", dynamic=True)

现在我只需要研究原因。只希望这个问题能为其他人节省几个小时...

关于python - 通过 Python 使用 ADO 将数据插入 MS Access 数据库时出现问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/638095/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com