{"id":4179,"date":"2023-11-04T23:14:07","date_gmt":"2023-11-04T23:14:07","guid":{"rendered":"http:\/\/localhost:10003\/how-to-implement-crud-operations-with-sqlite-and-python\/"},"modified":"2023-11-05T05:47:57","modified_gmt":"2023-11-05T05:47:57","slug":"how-to-implement-crud-operations-with-sqlite-and-python","status":"publish","type":"post","link":"http:\/\/localhost:10003\/how-to-implement-crud-operations-with-sqlite-and-python\/","title":{"rendered":"How to Implement CRUD Operations with SQLite and Python"},"content":{"rendered":"
SQLite is a lightweight, file-based database engine that is widely used in various applications and development scenarios due to its simplicity and ease of use. In this tutorial, we will explore how to implement CRUD (Create, Read, Update, and Delete) operations with SQLite using Python.<\/p>\n
Before we begin, make sure you have the following installed on your system:<\/p>\n
Once you have these prerequisites set up, let’s proceed with implementing CRUD operations with SQLite and Python.<\/p>\n
The first step is to create a SQLite database file and establish a connection to it using Python. To do this, follow the steps below:<\/p>\n
database.py<\/code>.<\/li>\n- Import the
sqlite3<\/code> module by adding the following line at the top of your file:<\/li>\n<\/ol>\nimport sqlite3\n<\/code><\/pre>\n\n- Create a connection to the database by running the following code:<\/li>\n<\/ol>\n
connection = sqlite3.connect('mydatabase.db')\n<\/code><\/pre>\nThis code establishes a connection to a SQLite database file named mydatabase.db<\/code>. If the file doesn’t exist, SQLite will create it automatically.<\/p>\nStep 2: Creating a Table<\/h2>\n
In this step, we will create a table in the database to store our data. For demonstration purposes, let’s imagine we want to create a simple contacts<\/strong> table with the following columns:<\/p>\n\n- id<\/strong>: A unique identifier for each contact.<\/li>\n
- name<\/strong>: The contact’s name.<\/li>\n
- email<\/strong>: The contact’s email address.<\/li>\n
- phone<\/strong>: The contact’s phone number.<\/li>\n<\/ul>\n
To create this table, add the following code after establishing the database connection:<\/p>\n
cursor = connection.cursor()\n\ncreate_table_query = '''\nCREATE TABLE IF NOT EXISTS contacts (\n id INTEGER PRIMARY KEY AUTOINCREMENT,\n name TEXT NOT NULL,\n email TEXT NOT NULL,\n phone TEXT NOT NULL\n);\n'''\n\ncursor.execute(create_table_query)\n<\/code><\/pre>\nThe cursor<\/code> object is used to execute SQL queries. In the create_table_query<\/code> variable, we define the SQL statement to create the contacts<\/strong> table if it doesn’t exist already.<\/p>\nNote that we use the IF NOT EXISTS<\/code> clause in the CREATE TABLE<\/code> statement to avoid re-creating the table if it already exists.<\/p>\nStep 3: Inserting Data<\/h2>\n
In this step, we will learn how to insert data into the contacts<\/strong> table. Suppose we have the following contact information:<\/p>\n\n- Name: John Doe<\/li>\n
- Email: john.doe@example.com<\/li>\n
- Phone: 123-456-7890<\/li>\n<\/ul>\n
To insert this data into the table, add the following code:<\/p>\n
insert_query = '''\nINSERT INTO contacts (name, email, phone)\nVALUES (?, ?, ?)\n'''\n\nvalues = ('John Doe', 'john.doe@example.com', '123-456-7890')\n\ncursor.execute(insert_query, values)\n\nconnection.commit()\n<\/code><\/pre>\nIn the insert_query<\/code> variable, we define the SQL statement to insert a new row into the contacts<\/strong> table with the provided values. The ?<\/code> placeholders are used as parameter markers to safely insert values into the query.<\/p>\nWe then define the values to be inserted in the values<\/code> variable. In this case, we use a tuple to store the name, email, and phone values.<\/p>\nFinally, we execute the query by calling the execute()<\/code> method on the cursor<\/code> object and pass the query and values as arguments. After executing the query, we commit the changes to the database using the commit()<\/code> method of the connection object.<\/p>\nStep 4: Retrieving Data<\/h2>\n
Now that we have inserted some data into the table, let’s learn how to retrieve it. To retrieve data from the contacts<\/strong> table, add the following code:<\/p>\nselect_query = '''\nSELECT * FROM contacts\n'''\n\ncursor.execute(select_query)\n\nrows = cursor.fetchall()\n\nfor row in rows:\n print(row)\n<\/code><\/pre>\nIn the select_query<\/code> variable, we define the SQL statement to retrieve all rows from the contacts<\/strong> table.<\/p>\nWe then execute the query by calling the execute()<\/code> method on the cursor<\/code> object. After executing the query, we call the fetchall()<\/code> method to retrieve all rows returned by the query.<\/p>\nFinally, we iterate over the rows using a simple for loop and print each row to the console.<\/p>\n
Step 5: Updating Data<\/h2>\n
In this step, we will learn how to update existing data in the contacts<\/strong> table. Suppose we want to update the phone number of the contact with an ID of 1 to “987-654-3210”.<\/p>\nTo update the data, add the following code:<\/p>\n
update_query = '''\nUPDATE contacts\nSET phone = ?\nWHERE id = ?\n'''\n\nvalues = ('987-654-3210', 1)\n\ncursor.execute(update_query, values)\n\nconnection.commit()\n<\/code><\/pre>\nIn the update_query<\/code> variable, we define the SQL statement to update the phone<\/strong> column of a row in the contacts<\/strong> table where the id<\/strong> matches a given value.<\/p>\nWe then define the new phone number and the ID of the contact to update in the values<\/code> variable.<\/p>\nAfter executing the query using the execute()<\/code> method, we commit the changes to the database using the commit()<\/code> method of the connection object.<\/p>\nStep 6: Deleting Data<\/h2>\n
In this step, we will learn how to delete data from the contacts<\/strong> table. Suppose we want to delete the contact with an ID of 1.<\/p>\nTo delete the data, add the following code:<\/p>\n
delete_query = '''\nDELETE FROM contacts\nWHERE id = ?\n'''\n\nvalues = (1,)\n\ncursor.execute(delete_query, values)\n\nconnection.commit()\n<\/code><\/pre>\nIn the delete_query<\/code> variable, we define the SQL statement to delete a row from the contacts<\/strong> table where the id<\/strong> matches a given value.<\/p>\nWe then define the ID of the contact to delete in the values<\/code> variable. Note that we use a comma after the ID value to create a tuple with a single element.<\/p>\nAfter executing the query using the execute()<\/code> method, we commit the changes to the database using the commit()<\/code> method of the connection object.<\/p>\nStep 7: Closing the Connection<\/h2>\n
Once you have finished working with the database, it’s important to close the connection properly. This ensures that all changes are saved, and the database file is released.<\/p>\n
To close the connection, add the following code at the end of your Python file:<\/p>\n
connection.close()\n<\/code><\/pre>\nThis will close the connection to the SQLite database.<\/p>\n
Conclusion<\/h2>\n
In this tutorial, we have explored how to implement CRUD operations with SQLite and Python. We learned how to create a database, establish a connection, create a table, insert data, retrieve data, update data, and delete data.<\/p>\n
SQLite provides a simple and efficient way to store and manage data in various applications and scenarios. By combining SQLite with Python, you can build powerful and flexible data storage solutions.<\/p>\n
Remember to always handle errors and exceptions properly when working with databases, as they can help you identify and resolve potential issues in your code.<\/p>\n
I hope you found this tutorial helpful. Now you have the knowledge to implement CRUD operations with SQLite using Python. Happy coding!<\/p>\n","protected":false},"excerpt":{"rendered":"
SQLite is a lightweight, file-based database engine that is widely used in various applications and development scenarios due to its simplicity and ease of use. In this tutorial, we will explore how to implement CRUD (Create, Read, Update, and Delete) operations with SQLite using Python. Prerequisites Before we begin, make Continue Reading<\/a><\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"_import_markdown_pro_load_document_selector":0,"_import_markdown_pro_submit_text_textarea":"","footnotes":""},"categories":[1],"tags":[1575,1576,85,75,1574],"yoast_head":"\nHow to Implement CRUD Operations with SQLite and Python - Pantherax Blogs<\/title>\n\n\n\n\n\n\n\n\n\n\n\n\n\n\t\n\t\n\t\n