![]() ![]() ![]() ![]() In this tutorial, you have learned how to develop a Python program to query data from tables in an SQLite database. Select_all_tasks(conn) Code language: Python ( python )ĭef create_connection (db_file): """ create a database connection to the SQLite databaseĭef select_task_by_priority (conn, priority): """ This main() function creates a connection to the database C:\sqlite\db\pythonsqlite.db and calls the functions to query all rows from the tasks table and select tasks with priority 1: def main ():ĭatabase = r"C:\sqlite\db\pythonsqlite.db" # create a database connection The fetchall() method fetched all matching tasks by the priority. Define the path to the database file using getDatabasesPath() from the sqflite package, combined with the join function from the path package. When the cursor executed the SELECT statement, it substituted the question mark ( ?) by the priority argument. The question mark ( ?) in the query is the placeholder. In the select_task_by_priority() function, we selected the tasks based on a particular priority. This function query tasks by priority: def select_task_by_priority (conn, priority): """Ĭur.execute( "SELECT * FROM tasks WHERE priority=?", (priority,)) In the select_all_tasks() function, we created a cursor, executed the SELECT statement, and called the fetchall() to fetch all tasks from the tasks table. Print(row) Code language: Python ( python ) This function selects all rows from the tasks table and displays the data: def select_all_tasks (conn): """ Return conn Code language: Python ( python ) In the following example, we will use the tasks table created in the creating tables tutorial.įirst, create a connection to an SQLite database specified by a file: def create_connection (db_file): """ create a database connection to the SQLite database Finally, loop the cursor and process each row individually.After that, call the fetchall() method of the cursor object to fetch the data.Next, create a Cursor object using the cursor method of the Connection object.First, establish a connection to the SQLite database by creating a Connection object.To query data in an SQLite database from Python, you use these steps: Summary: in this tutorial, we will show you step by step how to query data in SQLite from Python. ![]()
0 Comments
Leave a Reply. |