Home > Software engineering >  Python. Cannot place list items into individual variables. When I do, the variable contains the whol
Python. Cannot place list items into individual variables. When I do, the variable contains the whol

Time:03-06

def nextPage():
    conn = sqlite3.connect('xyz.db')
    c = conn.cursor()
   

    c.execute("INSERT INTO persons VALUES (?,?)",(text.get(),text1.get()))
        
    conn.commit()
    conn.close()

def submit():     
    conn = sqlite3.connect('xyz.db')
    c =conn.cursor()
    c.execute('''CREATE TABLE IF NOT EXISTS persons(
        name1 TEXT,
        name2 TEXT)''')        
    conn.commit()
    conn.close()


def query():
    conn = sqlite3.connect('xyz.db')
    c = conn.cursor()
    c.execute('SELECT * FROM persons')

    records = c.fetchall()
    print(records[0])
    conn.commit()
    conn.close()


import sqlite3
from tkinter import *
from tkinter import ttk
import tkinter as tk
ws = Tk()
ws.geometry('770x400')
ws.title('PythonGuides')

a = Label(ws ,text = "Name").grid(row = 1,column = 0)
b = Label(ws ,text = "Name of Spouse or CP, if applicable").grid(row = 2,column = 0)
text = Entry(ws)
text.grid(row = 1 , column = 1)

text1 = Entry(ws)
text1.grid(row = 2 , column = 1)

btn = ttk.Button(ws ,text="Submit", command = submit).grid(row=4,column=0)

Button(
    ws, 
    text="Next Page", command=nextPage).grid(row = 5,column = 10)

query()

ws.mainloop

#OUTPUT
#('JOHN', '')

I am working on a project using Tkinter and sqlite. Even thou I wanted to print only the 1st item from the list, the whole list was outputted. I want to place the items into individual variables, but each time, the whole list gets stored into a variable. Any help would be appreciated.

CodePudding user response:

I suppose the problem is the line records = c.fetchall(). fetchall() returns a list of tuples, where each tuple is a row from the database. So when you then print(records[0]), you're printing the entire first tuple.

To troubleshoot, try print(records), to print the entire list records, and see what that one looks like. You can then adjust the indexing of your print function to print only the exact stuff you wantt to print.

CodePudding user response:

records = c.fetchall()
print(records[0])

The value stored into records is a list of tuples, so records[0] is a tuple.

In Python tuples are iterables, so that are indexed and are accessibles like lists:

print(records[0][0])

CodePudding user response:

Thank you so much for your comments and putting me in the right direction. Thank you all.

  • Related