Search code examples
python-3.10

I am struggling to select a string of data from a database table and print it as a variable


I've been trying to learn how to use sqlite3 for python 3.10 and I can't find any explanation of how I'm supposed to grab saved data From a database and insert it into a variable.

I'm attempting to do that myself in this code but It just prints out <sqlite3.Cursor object at 0x0000018E3C017AC0>

Anyone know the solution to this?

My code is below

import sqlite3

con = sqlite3.connect('main.db')
cur = con.cursor()

#Create a table called "Datatable" if it does not exist
cur.execute('''CREATE TABLE IF NOT EXISTS datatable
                    (Name PRIMARY KEY, age, pronouns) ''')
# The key "PRIMARY KEY" after Name disallow's information to be inserted
# Into the table twice in a row.

name = 'TestName'#input("What is your name? : ")
age = 'TestAge'#input("What is your age? : ")

def data_entry():
    cur.execute("INSERT INTO datatable (name, age)")

con.commit

name = cur.execute('select name from datatable')

print(name)

Expected result from Print(name) : TestName Actual result : <sqlite3.Cursor object at 0x00000256A58B7AC0>


Solution

  • The execute statement fills the cur object with data, but then you need to get the data out:

        rows = cur.fetchall()
        for row in rows:
            print(row)
    

    You can read more here: https://www.sqlitetutorial.net/sqlite-python/sqlite-python-select/