[英]Best way to retrieve database results for further use?
I am working heavily with a database, using python, and I am trying to write code that actually makes my life easier. 我正在使用python大量处理数据库,并且正在尝试编写实际上使我的生活更轻松的代码。
Most of the time, I need to run a query and get results to process them; 大多数时候,我需要运行查询并获取结果以对其进行处理。 most of the time I get the same fields from the same table, so my idea was to collect the various results in an object, to process it later. 大多数时候,我从同一张表中获得相同的字段,所以我的想法是将各种结果收集到一个对象中,以供日后处理。
I am using SQLAlchemy for the DB interaction. 我正在使用SQLAlchemy进行数据库交互。 From what I can read, there is no direct way to just say "dump the result of this query to an object", so I can access the various fields like 据我了解,没有直接的方法可以直接说“将查询结果转储到对象中”,因此我可以访问各个字段,例如
print object.fieldA
print object.fieldB
and so on. 等等。 I tried dumping the results to JSON, but even that require parsing and it is not as straightforward as I hoped. 我尝试将结果转储到JSON,但是即使那样也需要解析,并且它不像我希望的那么简单。
So at this point is there anything else that I can actually try? 那么,在这一点上还有什么我可以尝试的吗? Or should I write a custom object that mimic the db structure, and parse the result with for loops, to put the data in the right place? 还是应该编写一个模仿db结构的自定义对象,并使用for循环解析结果,以将数据放置在正确的位置? I was hoping to find a way to do this automatically, but so far it seems that the only way to get something close to what I am looking for, is to use JSON. 我希望找到一种自动执行此操作的方法,但到目前为止,似乎使我所寻找的东西更接近的唯一方法是使用JSON。
EDIT: Found some info about serialization and the capabilities that SQLAlchemy has, to read a table and reproduce a sort of 1:1 copy of it in an object, but I am not sure that this will actually work with a query. 编辑:找到了一些有关序列化和SQLAlchemy具有的功能的信息,以读取表并在对象中重现该表的1:1副本,但是我不确定这是否可以与查询一起使用。
Found that the best way is to actually use a custom object. 发现最好的方法是实际使用自定义对象。
You can use reflection trough SQLAlchemy to extrapolate the structure, but if you are dealing with a small database with few tables, you can simply create on your own the object that will host the data. 您可以使用反射槽SQLAlchemy来推断结构,但是如果您要处理的是一个只有几个表的小型数据库,则可以简单地自己创建将承载数据的对象。 This gives you control over the object and what you can put in it. 这使您可以控制对象以及可以放置的对象。
There are obvious other ways, but since nobody posted anything; 还有其他明显的方法,但是由于没有人张贴任何东西; I assume that either are too easy to be mentioned, or too hard and specific to each case. 我认为要么太容易被提及,要么太难并且针对每种情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.