Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
216 views
in Technique[技术] by (71.8m points)

sql - Python Sqlite3 get value from table, like a dictionary

I have a database with values like this stored in a .db file. [UUID : INTEGER]

1e1f3e6e-c6e6-4897-8bb8-d732a1f5b303 : 12

2b0978c1-3f5b-4c7e-9151-231e0a21d2e3 : 128

4eba65c7-b02f-4627-8205-172333951d39 : 1

4baa130f-fe5b-45c7-9a44-842a6544d4a9 : 73

99fc3095-0aaa-4b19-aa2e-65b027bfd6ad : 7342

I would like to use the UUID to get an integer, like you would in a dictionary. Such as mydatabase["99fc3095-0aaa-4b19-aa2e-65b027bfd6ad"] would return 7342. So far all I have seen about getting values does not work in this way.

question from:https://stackoverflow.com/questions/65940244/python-sqlite3-get-value-from-table-like-a-dictionary

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

You can easily implement such class.

class DBMap:
    def __del__(self):
        self.conn.close()

    def __init__(self):
        self.conn = sqlite3.connect('map.db')

    def __getitem__(self, uuid):
        val = self.conn.execute(
            'select val from m where uuid = ?', (uuid,)
        ).fetchone()
        if val:
            return val[0]
        else:
            raise KeyError

On __init__, the connection to database is established and it is closed when __del__eted. __getitem__ is to implement evaluation of self[key]. So you can do the following:

dbm = DBMap()
print(dbm['aaa'])

Here is the .schema I used.

create table m (
    uuid TEXT NOT NULL UNIQUE,
    val  INTEGER
)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...