(Python SQLite) Select data from 1 specific column to use in a variable?

59 Views Asked by At

I am storing data in a database and want to retrieve data from one column but I'm only taking the data from one single cell, but the data it spits out with .fetchone() comes out as: (TheData, ).

I am using aiosqlite, which is the async library of sqlite.

db = await aiosqlite.connect('main.sqlite')
c = await db.cursor()
await c.execute(f"SELECT modchannel FROM sconfig WHERE guild_id = {ctx.guild.id}")
sresult = await c.fetchone()
print(sresult)

This is loading my main DB, looks into the sconfig table where I have, as an example:

guild_id modchannel
12345 RandomData
67890 MoreData

Now, this code works and it indeed does select the correct column I want, from the row I want, but it grabs the data (Lets say from 12345's Row) which would be in this pseudo case: RandomData but when stored in a variable it shows it as: ('RandomData',)

Currently I've just been doing the following to strip the stuff around the data away:

result = "".join(map(str, sresult))

Which then sets a new variable "result" with the data looking like: RandomData Looks like a good solution but I'm sure this isn't the correct way to select a single cells data, there must be a way to get that data without needing to use join map, as other datatypes may get messed up in future with this method.

I'm wanting to store date / time data soon and I fear the join map may break that data when taking it from the cell to use in variables.

I'm very new to databases so any help is appreciated and I hope my examples explain my problem. Oh and, I have seen resources saying that the select is storing data in a tuple, so I need to iterate over the values, etc etc, but I'm using async and unsure if theres a way to do that in async with the library i'm using and hoping there may be a simple way of querying the DB to return just that one cell of data, as that's what I'm asking for, not a row of data or a list of columns.

1

There are 1 best solutions below

0
Nik On

UPDATE Okay, I think I may have actually solved my own problem, but I welcome any other feedback from others.

What I've done now is assign row_factory so it indexes (correct term?) all the results (even though its technically one, but python treats every output as a tuple) and then I can assign a variable from that.

Like so:

db = await aiosqlite.connect('main.sqlite')
db.row_factory = aiosqlite.Row
c = await db.cursor()
await c.execute(f"SELECT modchannel FROM sconfig WHERE guild_id = {ctx.guild.id}")
sresult = await c.fetchone()
print(sresult) #Still prints the tuple, so it shows: **('RandomData',)**
print(f"TEST: {sresult['modchannel']}") #Prints: RandomData
test = sresult['modchannel'] #Assigns RandomData as a string to test variable
print(f'TEST VARIABLE: {test}') #Test variable only contains the data: RandomData

So this works better than my joinmap solution.