Python SQLite
Python SQLite:
SQLite is a C library that provides a lightweight disk-based database that doesn’t require a separate server process. It allows accessing the database using a nonstandard variant of the SQL query language. Some applications can use SQLite for internal data storage. It’s also possible to prototype an application using SQLite and then port the code to a larger system such as PostgreSQL or Oracle.
In Python, sqlite3
module is used to work with SQLite database. It’s a built-in module in Python, so you don’t need to install it separately.
Here’s a simple example of how to create a connection, create a table, insert data, and fetch data from SQLite database in Python:
import sqlite3
# Connect to the SQLite database
# If the database does not exist, it will be created
connection = sqlite3.connect('test.db')
# Create a cursor object
cursor = connection.cursor()
# Create a table
cursor.execute('''CREATE TABLE stocks
(date text, trans text, symbol text, qty real, price real)''')
# Insert a row of data
cursor.execute("INSERT INTO stocks VALUES ('2023-07-10','BUY','RHAT',100,35.14)")
# Save (commit) the changes
connection.commit()
# Fetch all rows from the table
cursor.execute("SELECT * FROM stocks")
print(cursor.fetchall())
# Close the connection
connection.close()
Remember to always call the commit()
function after executing an INSERT
, UPDATE
, or DELETE
statement. This function saves the changes. If you forget to call this function, the changes will not be saved. To close the connection to the database, use the close()
function.
In the example above, the database file test.db
is created in the current directory and the stocks
table is created in the test.db
database. The execute()
function is used to run SQL queries from Python.
Be aware that the approach used above (direct string formatting) can be subject to SQL injection attacks. It’s better to use parameterized queries to ensure the integrity and security of your data.
Here’s an example:
# Safe data insertion
cursor.execute("INSERT INTO stocks VALUES (?,?,?,?,?)", ('2023-07-10','BUY','RHAT',100,35.14))
This will safely format and include the values into the SQL command, protecting against SQL injection.
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