Python With SQL Databases - Full Crash Course | Python Database Connectivity Tutorial
SQLite is a popular, open-source, embedded relational database management system that is used in many applications and devices. It is lightweight, easy to use, and requires minimal setup, making it a good choice for storing and manipulating data in Python.
In this tutorial, we will explore how to connect Python with SQLite, the most widely deployed SQL database engine in the world. We will cover everything from installation and setup to basic CRUD operations (create, read, update, delete) and more advanced concepts such as prepared statements and transaction management.
To get started, you will need to have Python and SQLite installed on your computer. If you do not already have Python installed, you can download it from the official Python website (https://www.python.org/). For this tutorial, we will be using Python 3.9, but earlier versions should work as well.
SQLite is included with Python by default, so you do not need to install it separately. You can access the SQLite API in Python through the sqlite3 module, which is part of the standard library.
To connect to an SQLite database in Python, we can use the connect() function of the sqlite3 module, which takes the name of the database file as an argument. If the file does not exist, it will be created automatically.
import sqlite3 # Connect to the database cnx = sqlite3.connect("my_database.db")
# Create a cursor cursor = cnx.cursor() # Execute a SQL query cursor.execute("SELECT * FROM users") # Fetch the results results = cursor.fetchall() # Print the results print(results)
# Insert a new record cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John Smith", "john@example.com")) # Commit the changes to the database cnx.commit()
# Create a prepared statement stmt = "INSERT INTO users (name, email) VALUES (?, ?)" # Execute the prepared statement with different parameter values cursor.execute(stmt, ("Bob Smith", "bob@example.com")) cursor.execute(stmt, ("Alice Smith", "alice@example.com")) # Commit the changes to the database cnx.commit()
# Disable autocommit cnx.autocommit = False try: # Execute multiple statements as a single transaction cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("John Smith", "john@example.com")) cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ("Jane Doe", "jane@example.com")) # Commit the changes cnx.commit() except Exception as e: # Rollback the changes on error cnx.rollback() # Enable autocommit cnx.autocommit = True
Post a Comment
3 Comments
thanks tomi
ReplyDeleteThis comment has been removed by the author.
ReplyDeleteThis comment has been removed by the author.
ReplyDelete