News from this site

 Rental advertising space, please contact the webmaster if you need cooperation


+focus
focused

classification  

no classification

tag  

no tag

date  

no datas

Store database query result in an object in Python 3

posted on 2024-12-02 22:05     read(489)     comment(0)     like(30)     collect(1)


In my python application I run a query which returns me a product from my product table. When I get the result and assign it in a variable, it is stored in a list. But I want to create a product class and want to store query result in an object of my product class which matches with my database table.

But I dont want to do it in this way which is one by one getting values from list and setting object variables and so on.

I want to do this because my database table is large and list does not store variable's field names. It comes like following; so I cant use something like this; getProductName()

[5,"strawberry",011023234,10.5]

so I should remember in which position my product barcode code is stored when it is needed.

Retrieve data from database;

vt = sqlite3.connect("vt.sqlite")
im = vt.cursor()
im.execute("SELECT * FROM Products WHERE barcode='{}'".format(barcode))
veriler = im.fetchall()

Here is veriler = [5,"starberry",001].

My database table will be large. Then my veriler will be a long list.

When I want to get some attribute of retrieved data I have to access it like veriler[0], veriler[25] etc. I should remember indexes for each attribute.

Is it possible if I had product class which has all attributes in my database table and create a product object and when I assigned the database result to my product object I have set all attributes in product object and can access attributes of my product object using get methods.

Thanks in advance.


solution


Okay I think found out how to do it with some more searching.

Not sure it is the best way but it worked for me.

Convert database result into json and than convert json to python object.



Category of website: technical article > Q&A

Author:qs

link:http://www.pythonblackhole.com/blog/article/247231/1e8cceff1d8df725d9c0/

source:python black hole net

Please indicate the source for any form of reprinting. If any infringement is discovered, it will be held legally responsible.

30 0
collect article
collected

Comment content: (supports up to 255 characters)