DEV Community

CoderLegion
CoderLegion

Posted on • Originally published at coderlegion.com

1

ThDatabase Interaction using Python: Introduction to SQLite/MySQL/PostgreSQLis is a test article

⚡ Before you dive into this article... Check out our new community at CoderLegion.com! Share your knowledge, connect with like-minded developers, and grow together. Click here to join now!

The article covers POSTGRESQL, MySQL, and SQLITE3—three major database management systems. They provide unique features and benefits and are essential to software development. Let's explore their features so that you can make better selections that will improve the project. Together, let's explore these essential elements in modern software engineering.

As SQLite is lightweight, it is a great choice for embedded applications and situations where simplicity is essential. On the other hand, MySQL stands out thanks to its strong client-server design, scalability, and widespread industry acceptance. PostgreSQL, on the other hand, is a popular option for enterprise-level applications due to its versatility, dependability, and compliance with ACID short for Atomicity, Consistency, Isolation, and Durability.

SQLite Database
SQLite is a relational database engine that is lightweight, serverless, self-contained, and requires no configuration. Because it works directly with files, it's perfect for low-resource applications. Distribution and deployment are made easier by the fact that its self-contained databases are kept as single files.

Features:

Embedded in applications: SQLite, which is frequently integrated into programmes, allows internal data administration without the need for external servers. Data management is made easier by this, especially for offline functioning.
File-based database: SQLite databases are manageable and portable since they are kept as individual files on the file system.
Appropriate for small to medium-sized applications: Because of its simplicity and lightweight design, SQLite is especially well-suited for small to medium-sized applications, even though it can manage huge datasets as well.
Let's go through an example of defining tables, installing SQLite in Python, and carrying out CRUD (Create, Read, Update, Delete) operations:

conn = sqlite3.connect('example.db')
cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INTEGER PRIMARY KEY, name TEXT, email TEXT)''')
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Alice', 'Emails are not allowed'))
cursor.execute("INSERT INTO users (name, email) VALUES (?, ?)", ('Ali', 'Emails are not allowed'))
print("Records after initial insertion:")
cursor.execute("SELECT DISTINCT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.execute("UPDATE users SET email = ? WHERE name = ?", ('Emails are not allowed', 'Alice'))
print("\nRecords after updating email of Alice:")
cursor.execute("SELECT DISTINCT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
cursor.execute("DELETE FROM users WHERE name = ?", ('Alice',))
print("\nRecords after deleting Alice:")
cursor.execute("SELECT DISTINCT * FROM users")
rows = cursor.fetchall()
for row in rows:
print(row)
Output:

Tip: Make sure the 'DISTINCT' keyword is applied to the right columns in SQL queries to obtain unique value combinations and prevent accidental duplicate results.
MySQL Database
The popular open-source RDBMS MySQL provides strong features and dependability for systems ranging from small-scale initiatives to enterprise-level setups. It offers a wide range of tools and features for effective structured data management.

Features:

Client-server architecture:MySQL has a client-server design, which enables several clients to connect to the database server at once. The management of database resources, scalability, and security are all improved by this architecture.
Performance and scalability: MySQL is designed to be scalable, meaning it can manage big databases and high transaction volumes while maintaining optimal performance. Performance is improved by its effective caching, query optimisation, and indexing methods.
Broad industrial adoption: MySQL is widely used in a number of industries, including telecommunications, e-commerce, technology, and finance. Its widespread community support, dependability, and open-source nature have all added to its appeal.
You can get the MySQL Community Server package from mysql official website and install MySQL by following the given steps. As an alternative, you can use package managers such as Homebrew for macOS or apt-get for Linux.

Connecting to MySQL from Python:

import mysql.connector
conn = mysql.connector.connect(user='user', password='password',
host='localhost',
database='test')
cursor = conn.cursor()
cursor.execute("SELECT * FROM table_name")
results = cursor.fetchall()
conn.close()
Creating tables and executing queries using Python's MySQL Connector:

cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users
(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), email VARCHAR(255))''')
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ('Alice', 'Emails are not allowed'))
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()

PostgreSQL Database
Strong and open-source, PostgreSQL is an object-relational database system that is well-known for its feature-rich set, dependability, and extensibility. It is a top option for both small-scale applications and large corporate systems because of its comprehensive functions that enable complicated data types, transactions, and data integrity.

Features:

Extensibility: Because of PostgreSQL's flexible architecture, programmers are able to design unique functions, data types, and indexing techniques to meet the needs of particular applications. The smooth integration of third-party extensions and libraries is made possible by this flexibility.
ACID Compliance: PostgreSQL guarantees ACID (
Atomicity: To preserve database integrity, transactions are either fully completed or entirely aborted.
Consistency: Assures that the database is kept intact by writing only legitimate data.
Isolation: Data integrity is ensured by many transactions running simultaneously without interfering.
Durability: Even in the event of a system failure, committed transaction modifications remain intact.) compliance, which in turn provides dependable and consistent database transactions. This functionality is crucial for ensuring consistency across the database and data integrity even in the case of system failures.
Data Integrity and Reliability: PostgreSQL uses built-in restrictions like triggers and rules, foreign keys, and concurrency management to guarantee data integrity and stability.
To install PostgreSQL, you can download and install the PostgreSQL package from the official website.

import psycopg2
conn = psycopg2.connect(
dbname='your_database_name',
user='your_username',
password='your_password',
host='localhost',
port='5432'
)
if conn:
print("Connected to PostgreSQL")
else:
print("Failed to connect to PostgreSQL")
conn.close()
Creating tables and executing queries using Python's psycopg2 library:

Create a cursor object

cursor = conn.cursor()
cursor.execute('''CREATE TABLE IF NOT EXISTS users (
id SERIAL PRIMARY KEY,
name VARCHAR(255),
email VARCHAR(255)
)''')
cursor.execute("INSERT INTO users (name, email) VALUES (%s, %s)", ('Alice', 'Emails are not allowed'))
cursor.execute("SELECT * FROM users")
results = cursor.fetchall()
for row in results:
print(row)
conn.commit()
Note: Always securely handle database credentials and avoid hardcoding them directly into your code for better security.
Comparison
Factor SQLite MySQL PostgreSQL
Performance
Good for
small to medium
-sized applications

Optimized for
read-heavy
workloads Optimized for
complex
queries
and large
datasets
Scalability Limited scalability
due to file-
based architecture Good scalability
with support for
clustering and
sharding High scalability
with advanced
replication and
partitioning
Features Basic features with limited concurrency support Rich feature set including stored procedures, triggers, and views Comprehensive feature set including JSONB data type,
full-text search, and
advanced indexing
Ease of Use Simple setup and usage, suitable for beginners Easy to use, especially
with graphical tools like MySQL Workbench Requires more
configuration but
offers powerful features
Use Case Suitability Ideal for
embedded
systems
and small
applications

Well-suited for web applications
and medium-
sized databases

Best for large-scale applications with
complex data
requirements
Advanced Concepts
Advanced ideas like indexing, optimization, and transactions are essential for improving the scalability, performance, and dependability of databases.

Transactions: Transactions ensure the ACID properties of database operations, handling multiple tasks as a single unit for data accuracy and reliability. All database systems provide tools for effective transaction management.
Indexing: Indexes expedite data retrieval, particularly for SELECT queries, by swiftly accessing entries in database tables based on specific field values. Effective indexing reduces the need for full table scans, significantly enhancing query performance.
Optimization: Database optimization strategies improve effectiveness and performance through resource usage optimization, performance tuning, query optimization, and schema design optimization. Each system provides unique features and tools to enhance productivity and address performance issues.
import sqlite3
import mysql.connector
import psycopg2
def sqlite_transactions():
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
try:
conn.execute("BEGIN")
cursor.execute("UPDATE users SET balance = balance - 100 WHERE id = 1")
cursor.execute("UPDATE users SET balance = balance + 100 WHERE id = 2")
conn.commit()
print("Transaction committed successfully")
except sqlite3.Error as e:
conn.rollback()
print("Transaction rolled back due to error:", e)
finally:
conn.close()
def mysql_transactions():
conn = mysql.connector.connect(user='user', password='password', database='example')
cursor = conn.cursor()
try:
conn.start_transaction()
cursor.execute("UPDATE users SET balance = balance - 100 WHERE id = 1")
cursor.execute("UPDATE users SET balance = balance + 100 WHERE id = 2")
conn.commit()
print("Transaction committed successfully")
except mysql.connector.Error as e:
conn.rollback()
print("Transaction rolled back due to error:", e)
finally:
conn.close()
def postgres_transactions():
conn = psycopg2.connect(dbname='example', user='user', password='password', host='localhost')
cursor = conn.cursor()
try:
conn.autocommit = False
cursor.execute("UPDATE users SET balance = balance - 100 WHERE id = 1")
cursor.execute("UPDATE users SET balance = balance + 100 WHERE id = 2")
conn.commit()
print("Transaction committed successfully")
except psycopg2.Error as e:
conn.rollback()
print("Transaction rolled back due to error:", e)
finally:
conn.close()
sqlite_transactions()
mysql_transactions()
postgres_transactions()
SQLite, designed for single-user and small-scale applications, uses local file-based databases and simple transaction management with BEGIN, COMMIT, and ROLLBACK statements.
MySQL, a robust RDBMS, offers scalability and concurrency control with start_transaction(), commit(), and rollback() methods.
PostgreSQL, known for advanced features and extensibility, provides strong support for concurrency, data integrity, and advanced SQL features, managing transactions via autocommit mode and commit()/rollback() methods.

FAQ

Q: What is the difference between SQL and NoSQL databases?
A: SQL (Structured Query Language) databases, also known as relational databases, organize data into tables with predefined schemas and use SQL for querying. NoSQL databases, on the other hand, store data in flexible, non-tabular formats and do not require a fixed schema. They are designed for scalability and handling unstructured data.
Conclusion
Databases are essential to software development because they allow for effective data management. MySQL scales for the web, PostgreSQL meets enterprise needs, and SQLite is ideal for lightweight applications. When choosing a project, it is essential to comprehend their strengths. Using cutting-edge ideas promotes creativity in digital solutions by ensuring data performance and dependability.

Reference
For more reference:
SQLite Official Website:
SQLite Official Website

Heroku

Deploy with ease. Manage efficiently. Scale faster.

Leave the infrastructure headaches to us, while you focus on pushing boundaries, realizing your vision, and making a lasting impression on your users.

Get Started

Top comments (0)

AWS Q Developer image

Your AI Code Assistant

Automate your code reviews. Catch bugs before your coworkers. Fix security issues in your code. Built to handle large projects, Amazon Q Developer works alongside you from idea to production code.

Get started free in your IDE

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay