0

I want to create a search box that will get input from user, put it into an SQL query, and return matching records from the queried database.

Everything seems to work just fine - except I can't display my query results as a Pandas dataframe. The script just does when it should display the object. However, when I use print(), my result is displayed.

When I do it like this, nothing happens:

query = pd.read_sql(sql_string, connection)
query

But this works just fine:

query = pd.read_sql(sql_string, connection)
print(query)

This is my code:

import qgrid
from ipywidgets import widgets
from IPython.display import display

connection = 'connection:details'
text = widgets.Text()
display(text)

def handle_submit(a):
    user_input = text.value
    sp_char = "%"
    sql_string = "SELECT a FROM my_database WHERE UPPER(a) LIKE UPPER('%s%s%s') % (sp_char,user_input,sp_char)
    query = pd.read_sql(sql_string, connection)
    query

text.on_submit(handle_submit)

I'm pretty sure I'm doing something wrong with the way that variables are moved inside and outside of the def but I'm not really sure where to go from here.

EDIT:

Solved with ipywidget function display()

    query = pd.read_sql(sql_string, connection)
    display(qgrid.show_grid(query))

This is all I needed :)

gooseberry
  • 26
  • 5

1 Answers1

0

IPython does not print return values that are inside functions.

>>> a = 1
>>> a            # prints 1 because in global scope

>>> def foo():
        a = 2
        a        # prints nothing, even though a value is returned to the REPL
>>> foo()

>>> def baz():
        a = 2
        print(a) # prints 2
>>> baz()

Could you clarify what you mean by "my result is displayed"?

fizzybear
  • 1,197
  • 8
  • 22
  • By "my result is displayed" I mean: the data returned by the query is printed in text form below the cell. The script returns the result I want, but not in the form I want. – gooseberry Jul 03 '19 at 16:03
  • So why not just print(query) in `handle_submit`? What form do you actually want? – fizzybear Jul 03 '19 at 16:33
  • My dataset contains long string values - just printing it makes a mess of it. I need the returned data to be used in the same notebook cell - I want to display it using qgrid. Just putting *qgrid.show_grid(query)* also does nothing. – gooseberry Jul 04 '19 at 06:48
  • I think I have it! ```python query = pd.read_sql(sql_string, connection) display(qgrid.show_grid(query))``` This is all I needed :) – gooseberry Jul 04 '19 at 07:11