Here I have some simple python code to query a sqlite3 database.
import sqlite3 as lite
conn = lite.connect('db/posts.db')
cur = conn.cursor()
def get_posts():
cur.execute("SELECT * FROM Posts")
print(cur.fetchall())
get_posts()
I have already created the table Posts
. When I run this I get no errors, and it just prints out []
. I know that the table Posts isn't empty, I created it in a REPL. Why is this not working?
Any help is appreciated!
Create SQLite table from Python. Refer to Python SQLite database connection to connect to SQLite database. Next, prepare a SQLite SELECT query to fetch rows from a table. You can select all or limited rows based on your requirement. Next, use a connection.cursor () method to create a cursor object. This method returns a cursor object.
In this article, we will discuss, select statement of the Python SQLite module. This statement is used to retrieve data from an SQLite table and this returns the data contained in the table. In SQLite the syntax of Select Statement is: SELECT * FROM table_name;
Next, prepare a SQLite SELECT query to fetch rows from a table. You can select all or limited rows based on your requirement. Next, use a connection.cursor () method to create a cursor object. This method returns a cursor object. The Cursor object is required to execute the query. Execute the select query using the cursor.execute (query) method.
The sqlite3 docs sneak that into an example about input sanitization, and that's it. No later section for printing query results or anything. Super confusing.
Use a context manager, so you don´t have to commit!
def get_posts():
with conn:
cur.execute("SELECT * FROM Posts")
print(cur.fetchall())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With