0

I am using a SQLite3 db file to retrieve data and store it in a variable so that I can use it to display the results on a HTML table.

This is how I am storing the results from the query:

test = c.execute("SELECT column_name from table_name LIMIT 11")

However, when I try to display it in the table, using "{%for x in test%}", the output is being displayed like this: (1.234,). What do I need to change for the output to look like this: 1.234 so without the bracket and comma?

0

1 Answer 1

2

You want a list of all results of your query, you should use fetchall(), which, according to the docs:

Fetches all (remaining) rows of a query result, returning a list. Note that the cursor’s arraysize attribute can affect the performance of this operation. An empty list is returned when no rows are available.

Try this:

c = sqlite3.connect('db_path.db')
cur = c.cursor()
cur.execute("SELECT column_name from table_name LIMIT 11")
test = cur.fetchall()

Your html would then look like this:

<table>
  {% for row in test %}
  <tr>
    <th> {{ row[0] }}</th>
  </tr> 
  {% endfor %}
</table>
Sign up to request clarification or add additional context in comments.

10 Comments

"TypeError: 'sqlite3.Cursor' object is not subscriptable" I have tried this before
Okay I tried this and get this error "AttributeError: 'sqlite3.Connection' object has no attribute 'fetchone'" Also I am doing this "test = c.execute("SELECT column_name from table_name LIMIT 11)"
You should be doing this with a cursor. I thought c was a cursor, and not a connection. You should do cur = c.cursor(), then cur.execute("select ....") then test = cur.fetchone()[0]
Okay so this did something. Before my output was a list which filled the table in the output and since I was using a for loop to iterate through each item and output it in the table "{%for x in amsterdam%}" now it will not let me do that because its not a list anymore.
In your html, inside the {%for x in test%}, when you want to use the retrieved value, you should be using {{ x[0] }}, since fetchall returns a list of rows.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.