Home > Software design >  Python: Inserting TextBox value into SQLite Database
Python: Inserting TextBox value into SQLite Database

Time:05-05

I am trying to extract a TextBox content and insert it into an SQLite database. I am using the guizero module.

I've written this python test script

from guizero import App, PushButton,TextBox, Text,Box
import sqlite3

global x 
global name

def insertVaribleIntoTable(x):
    try:
        sqliteConnection = sqlite3.connect('DB')
        cursor = sqliteConnection.cursor()
        cursor.execute('''INSERT INTO employee VALUES (?)''',(x,))
        sqliteConnection.commit()

        cursor.execute('''SELECT emp_name FROM employee''')
        print("database content : \n")
        print(cursor.fetchall())
        cursor.close()

    except sqlite3.Error as error:
        print("Failed to insert Python variable into sqlite table", error)
    finally:
        if sqliteConnection:
            sqliteConnection.close()

def when_clicked():
    print(name)
    strname = str(name)
    print(strname)
    insertVaribleIntoTable(strname)
    name.clear()

app = App(title="Registration")

message = Text(app, text="Registration")
entrybox = Box(app, width=185, height='fill')
Text(entrybox, text='Name ', align='left')
name = TextBox(entrybox, align='left', width=185)
button = PushButton(app, text="Add", command=when_clicked)

app.display()

Now, In the TexyBox when I insert userAA and click the Add button, I am getting this output

database content :
[('User1',), ('User2',), ('User3',), ("[TextBox] object with text 'userAA'",)]

While the expected output is

database content :
[('User1',), ('User2',), ('User3',), ('userAA',)]

Does someone have any idea how to solve this problem ?

CodePudding user response:

It seems like you have a problem with name variable. It is an instance of TextBox class that inherits its __str__ method through chain: Component -> Widget -> TextWidget -> TextBox.

It looks like that:

def __str__(self):                                                                                                                                                                                          
    return self.description

Inside TextBox class:

@property
def description(self):
    """
    Returns the description for the widget.
    """
    return "[TextBox] object with text '{}'".format(self.value)

You can explore it here: https://github.com/lawsie/guizero/tree/master/guizero

So I think you should use something like that:

def when_clicked():
    print(name)
    strname = name.value  # str(name) will call name.descirption
    print(strname)
    insertVaribleIntoTable(strname)
    name.clear()
  • Related