0

I've been working on an SQL Basics project in Python and this is my code. When I run it, it should display my lines in a table but it doesn't. Using print(run_query(query)) works, but not the way I wrote it here:


import sqlite3

import pandas as pd

db = sqlite3.connect("hubway.db")

def run_query(query):
    return pd.read_sql_query(query, db)

query = 'SELECT * FROM trips LIMIT 5;'
run_query(query)

All of this is from https://www.dataquest.io/blog/sql-basics/. The database is nothing complicated, just two tables that contain some columns with data.

Almond75
  • 3
  • 3
  • Can you share your whole function if it's not long? Because there can be multiple problems. For example you are returning the values. Did you print them when you called the function/method? Is your database populated? Do you get an error or warning? – MSH Nov 02 '21 at 13:01
  • Get it in some variable. Data=run_query(query) check if it works – Faika Majid Nov 02 '21 at 14:41
  • @FaikaMajid I tried it and it works, in the sense that data = run_query(query) gives me no errors, and print(data) prints out the data correctly, same as print(run_query(query)). But I shouldn't need a print to display the data, since pd.read_sql is supposed to do it automatically. – Almond75 Nov 03 '21 at 17:54
  • @MSH I clarified some of these in my question, I think it should be clearer now. – Almond75 Nov 03 '21 at 17:57
  • Yes, you don't need to print it, you can now return this data, wherever you want to use it. – Faika Majid Nov 04 '21 at 04:39

1 Answers1

0

Your function is returning a value which is the respond to your sql request.

The key word here is returning. Means you can assign your respond (run_query) to a variable:

import sqlite3

import pandas as pd

db = sqlite3.connect("hubway.db")

def run_query(query):
    return pd.read_sql_query(query, db)

query = 'SELECT * FROM trips LIMIT 5;'
respond = run_query(query)

Now you can use the variable respond as you wish. For example you can print it.

If you want your function to only print the respond of the sql query you should use print function instead of return statement:

import sqlite3

import pandas as pd

db = sqlite3.connect("hubway.db")

def run_query(query):
    print(pd.read_sql_query(query, db))

query = 'SELECT * FROM trips LIMIT 5;'
run_query(query)

This may be more clear: What is the purpose of the return statement?

MSH
  • 1,743
  • 2
  • 14
  • 22