我正在尝试从数据库 (MS-Access) 读取数据,操作它们,然后在创建新表后将它们写回。 基本上一切正常(读、写、创建表),但我面临的问题如下:
首先我创建的表有5个字段,类型如下:
Types = ['integer', 'varchar(12)', 'integer', 'double', 'date']
我想写的数据是这样的形式:
Items = ['1', 'Widgit', '5.0', '15.1234', '2009-01-29 13:05:30']
如您所见,数据元素的类型为 str。所以通常我应该做类似的事情:
[Type(Item) for (Type, Item) in zip(Types, Items)]
但这行不通,因为我的类型不是 pythonic。
有什么想法吗?
请您参考如下方法:
您能否使用一个小函数将“数据库”类型映射到“Python”类型,也许是这样的?
def get_py_type(access_type):
if access_type == "integer":
return "int"
elif access_type.startswith("varchar"):
return "str"
elif access_type == "double":
return "float"
elif access_type == "date":
return "datetime"
else:
return "unknown"
这样您就可以将现有列表映射到 Python 类型列表
>>> Types = ['integer', 'varchar(12)', 'integer', 'double', 'date']
>>> pyTypes = [get_py_type(item) for item in Types]
>>> print pyTypes
['int', 'str', 'int', 'float', 'datetime']
>>>
然后从那里继续?
