SQLite3 Python
SQLite3 Python:
SQLite is a self-contained, serverless, and zero-configuration database engine. It’s one of the most widely deployed database engines in the world and is used in a broad range of applications. Python has built-in support for SQLite in the sqlite3
module in its standard library.
Here’s a basic example of how to use SQLite in Python:
- Import the module:
import sqlite3
- Connect to the SQLite database. If the database does not exist, SQLite will create it:
connection = sqlite3.connect('test.db')
- Create a Cursor object. You’ll use this object to execute all your SQL commands:
cursor = connection.cursor()
- Execute a SQL command. In this case, let’s create a table:
cursor.execute('''CREATE TABLE employees
(first_name text, last_name text, pay int)''')
- Insert a row of data:
cursor.execute("INSERT INTO employees VALUES ('John','Doe',50000)")
- Save (commit) the changes:
connection.commit()
- Close the connection. If you’ve made any changes to the database that haven’t been committed yet, this will automatically commit them before closing:
connection.close()
To retrieve data, you’d use a SELECT
statement:
cursor.execute("SELECT * FROM employees WHERE last_name='Doe'")
print(cursor.fetchall())
This will print all rows where the last name is ‘Doe’.
This is a basic introduction to using SQLite in Python. Depending on your needs, you might also want to look into using parameterized queries (to prevent SQL injection attacks), using cursor.fetchone()
or cursor.fetchmany(n)
instead of cursor.fetchall()
, and handling transactions explicitly.
Python Training Demo Day 1
Conclusion:
Unogeeks is the No.1 IT Training Institute for Python Training. Anyone Disagree? Please drop in a comment
You can check out our other latest blogs on Python here – Python Blogs
You can check out our Best In Class Python Training Details here – Python Training
Follow & Connect with us:
———————————-
For Training inquiries:
Call/Whatsapp: +91 73960 33555
Mail us at: info@unogeeks.com
Our Website ➜ https://unogeeks.com
Follow us:
Instagram: https://www.instagram.com/unogeeks
Facebook: https://www.facebook.com/UnogeeksSoftwareTrainingInstitute
Twitter: https://twitter.com/unogeeks