Reputation: 926
Trying to get a value from sqlite3 and convert it to a string and store it in a variable
import sqlite3
conn = sqlite3.connect('mydb.db')
database = conn.cursor()
u = 'ZERO'
all_data = str(database.execute("SELECT * FROM logs where loguser =? ", (u,)).fetchone())
Results:
(5, 'ZERO', hello there !')
I tried :
x = ''.join(all_data)
print(x)
What I'm hoping for :
5 ZERO hello there !
Upvotes: 1
Views: 2066
Reputation: 21932
When you run fetchone()
, you get a tuple back, which represents the row in your database table, so that column's value is an element in the tuple:
(5, 'ZERO', 'hello there !')
Which you then converted to a string with str()
:
>>> all_data = str((5, 'ZERO', 'hello there !'))
>>> all_data
"(5, 'ZERO', 'hello there !')"
And you converted it to a string before you stored the value to all_data
, which is why your ''.join()
did nothing:
>>> ''.join('abcdefg')
'abcdefg'
You clearly don't want the commas and parenthesis, so we shouldn't convert the result of fetchone()
to a string in the first place. Let's just get the tuple first:
>>> data = database.execute(...).fetchone()
>>> data
(5, 'ZERO', 'hello there !')
Now join the tuple's elements together, separated with spaces (as you've asked) using:
' '.join(data)
This will not work if you have non-string elements in the tuple (in your case the 5
), so you need to convert everything to strings before you join them. I recommend using a comprehension:
' '.join(str(column) for column in data)
This will give you the desired final string:
>>> data_str = ' '.join(str(x) for x in data)
>>> data_str
'5 ZERO hello there !'
Upvotes: 1