Database Mysql
Database Mysql
Database Mysql
One of the freely available, reliable and popular databases is MySQL and we will be studying more about same in this
series.
Before we proceed to explain the MySQL database system, let us have a look at few definitions related to the
database which are in general applicable to any other relational databases as well.
2. Table - A table is a matrix with data. A table in a database looks like a simple spreadsheet.
3. Column - One column (data element) contains data of one and the same kind, for example, the column
postcode.
4. Row - A row (= tuple, entry or record) is a group of related data, for example, the data of one subscription.
5. Redundancy - Storing data twice in more than one tables, redundantly to make the system faster.
6. Primary Key - A primary key is unique. A key value can not occur twice in one table. With a key, you can only
find one row. A table will have only one Primary Key
7. Unique Key - A unique key is a combination of one or more columns which can uniquely identify a row in the
table. That combination cannot occur more than once in one table excluding rows having NULL values in key
columns. A table can have more than one unique key.
8. Compound Key - A compound key (composite key) is a key that consists of multiple columns because one
column is not sufficiently unique. Another term for the unique key which has more than one column.
11. Referential Integrity - Referential Integrity makes sure that a foreign key value always points to an existing
row.
Here’s a comprehensive overview of the key concepts covered in the CBSE Class 12th CS Unit 3 notes:
Relational data model: relation, attribute, tuple, domain, degree, cardinality, keys (candidate key, primary
key, alternate key, foreign key)
Structured Query Language: introduction, Data Definition Language and Data Manipulation Language, data
type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key), create database, use
database, show databases, drop database, show tables, create table, describe table, alter table (add and
remove an attribute, add and remove primary key), drop table, insert, delete, select, operators
(mathematical, relational and logical), aliasing, distinct clause, where clause, in, between, order by, meaning
of null, is null, is not null, like, update command, delete command, aggregate functions (max, min, avg, sum,
count), group by, having clause, joins: cartesian product on two tables, equi-join and natural join
Interface of python with an SQL database: connecting SQL with Python, performing insert, update, delete
queries using cursor, display data by using connect(), cursor(), execute(), commit(), fetchone(), fetchall(),
rowcount, creating database connectivity applications, use of %s format specifier or format() to perform
queries.
Table of Content
Database Concepts
CBSE Class 12th Computer Science Unit III Notes: Marks Distribution
Database Concepts
Databases are essential components of modern computing that store, manage, and retrieve data efficiently. Here’s
an overview of what databases are, their key concepts, and why they are important.
What is a Database?
Definition: A database is an organized collection of data stored electronically. It allows for easy access, management,
and updating of data. Databases can range from simple lists to complex systems handling large volumes of
information.
Components:
Tables: The basic building blocks where data is stored. Each table consists of rows (records) and columns
(fields).
Records: Individual entries in a table, representing a specific data instance (e.g., a single customer’s details).
Fields: The columns in a table, defining the type of data stored (e.g., name, email, address).
Definition: Software that manages and controls access to databases. It allows users to create, update, and
query databases.
Schema:
Definition: The structure or blueprint of a database, defining how data is organized and how relationships
between data are handled. It includes definitions of tables, fields, and their relationships.
Example: A schema might define tables for customers, orders, and products, and specify how these tables
are related.
Architecture of DBMS
Query Language:
Definition: A language used to interact with a database, primarily to retrieve, update, or manipulate data.
Examples: SQL (Structured Query Language) is the most common language used for querying databases.
Normalization:
Definition: The process of organizing data in a database to reduce redundancy and improve data integrity. It
involves dividing large tables into smaller, related tables.
Example: Separating customer information from order details to avoid duplication of customer data.
Indexing:
Definition: A technique used to speed up data retrieval operations by creating indexes on database columns.
Example: Creating an index on the “email” column in a customer table to quickly find records by email
address.
Need: Organizes large amounts of data systematically, making it easier to retrieve, update, and manage
information.
Benefit: Reduces time and effort required to handle and process data.
Data Integrity:
Benefit: Minimizes errors and maintains the quality of data over time.
Data Security:
Benefit: Safeguards confidential information and complies with legal and regulatory requirements.
Concurrent Access:
Need: Allows multiple users to access and work with the database simultaneously without conflicts.
Scalability:
Need: Supports the growth of data and the increasing complexity of data management needs.
Benefit: Ensures that the database can handle expanding amounts of information and user demands.
The relational data model is a way of structuring data using relations (tables). It is fundamental to relational
databases and organizes data into tables with rows and columns. Here’s a breakdown of key concepts in the
relational data model:
1. Relation
Definition: A relation, or table, is a collection of tuples (rows) that share the same attributes (columns). It
represents a specific type of entity or relationship in the database.
Example: A table called Students that includes information about students, where each row represents a
student.
2. Attribute
Definition: An attribute is a column in a table that represents a specific property or characteristic of the
entity described by the table. Each attribute has a name and a data type.
Example: In the Students table, attributes might include StudentID, Name, and DateOfBirth.
3. Tuple
Definition: A tuple is a single row in a table. It represents a specific instance of the entity or relationship
described by the table.
Example: In the Students table, a tuple might be (123, ‘Alice Smith’, ‘2005-05-15’), representing a specific
student.
Relational Data Model
4. Domain
Definition: A domain is the set of permissible values that an attribute can take. It defines the type of data
that can be stored in a column, such as integer, string, or date.
Example: For the attribute DateOfBirth, the domain might be all valid date values.
5. Degree
Definition: The degree of a relation (table) is the number of attributes (columns) it has. It indicates the
number of different pieces of information stored for each tuple.
Example: If the Students table has three attributes (StudentID, Name, DateOfBirth), its degree is 3.
6. Cardinality
Definition: The cardinality of a relation (table) is the number of tuples (rows) it contains. It represents the
size of the table and the number of instances of the entity.
Example: If the Students table has 100 rows, its cardinality is 100.
Keys are fundamental to relational databases as they uniquely identify rows within a table and establish relationships
between tables. Here’s an overview of different types of keys:
1. Candidate Key
Definition: A candidate key is an attribute or a set of attributes that can uniquely identify each tuple (row) in a table.
A table can have multiple candidate keys, but each one is a potential primary key.
Characteristics:
2. Primary Key
Definition: The primary key is a specific candidate key chosen to uniquely identify each tuple in a table. It ensures
that each row is unique and not null.
Characteristics:
Example: In the Students table, StudentID might be selected as the primary key.
3. Alternate Key
Definition: An alternate key is any candidate key that is not chosen as the primary key. It is still a unique identifier for
tuples but is not used as the main key for the table.
Characteristics:
Used for ensuring uniqueness in case the primary key is not suitable.
Example: If StudentID is chosen as the primary key, then Email (if unique) becomes an alternate key.
4. Foreign Key
Definition: A foreign key is an attribute or a set of attributes in one table that refers to the primary key of another
table. It establishes and enforces a link between the data in the two tables.
Characteristics:
Ensures referential integrity by enforcing that the value in the foreign key column matches a value in the
primary key column of the related table.
Introduction to SQL
Structured Query Language (SQL) is a standardized programming language used for managing and manipulating
relational databases. SQL allows users to create, modify, and query databases effectively. It provides a way to interact
with data stored in relational database management systems (RDBMS).
Purpose: SQL is designed to handle tasks such as querying data, updating records, and managing database
structures. It provides a straightforward syntax for interacting with relational databases.
Components: SQL is divided into several categories based on the type of operations it supports.
Data Definition Language (DDL) is a subset of SQL used for defining and managing database structures. It includes
commands that define, alter, and drop database objects such as tables, indexes, and schemas.
CREATE: Used to create new database objects, such as tables, indexes, and views
o Example: CREATE TABLE Students (StudentID INT PRIMARY KEY, Name VARCHAR(50), DateOfBirth
DATE)
ALTER: Used to modify existing database objects, such as adding or deleting columns in a table.
TRUNCATE: Used to remove all records from a table without deleting the table structure.
Data Manipulation Language (DML) is a subset of SQL used for manipulating and querying the data stored in the
database. It includes commands to insert, update, delete, and retrieve data.
SELECT: Retrieves data from one or more tables. It can include conditions, sorting, and grouping
o Example: INSERT INTO Students (StudentID, Name, DateOfBirth) VALUES (1, ‘Alice Smith’, ‘2005-05-
15’)
Summary
SQL: A language used to interact with relational databases, allowing for the creation, modification, and
querying of database structures and data.
Data Definition Language (DDL): Includes commands for defining and managing database objects (CREATE,
ALTER, DROP, TRUNCATE).
Data Manipulation Language (DML): Includes commands for manipulating and querying data (SELECT,
INSERT, UPDATE, DELETE).
Data Type (char(n), varchar(n), int, float, date), constraints (not null, unique, primary key)
SQL data types define the kind of data that can be stored in a database column. Constraints are rules applied to
columns to ensure data integrity and enforce specific data conditions.
Data Types
CHAR(n)
Definition: A fixed-length character string. If the data stored is shorter than n characters, it is padded with
spaces.
Usage: Useful for storing data with a consistent length, such as country codes or status codes.
Example: CHAR(10) will store exactly 10 characters; “ABC” becomes “ABC ” (with padding).
VARCHAR(n)
Definition: A variable-length character string. Only the actual number of characters is stored, up to n
characters.
Usage: Ideal for storing text data of varying lengths, such as names or addresses.
Example: VARCHAR(50) will store up to 50 characters. “John” will use only 4 characters of space.
INT
Definition: A whole number. It can store both positive and negative integers.
FLOAT
Definition: A floating-point number, which can store decimal values. It’s used for precise calculations and
measurements.
Usage: Suitable for storing values with decimals, such as prices or scientific measurements.
DATE
Constraints
Constraints are the rules that we can apply on the type of data in a table. That is, we can specify the limit on the type
of data that can be stored in a particular column in a table using constraints.
We can specify constraints at the time of creating the table using CREATE TABLE statement. We can also specify the
constraints after creating a table using ALTER TABLE statement.
Syntax:
Below is the syntax to create constraints using CREATE TABLE statement at the time of creating the table.
NOT NULL
Definition: Ensures that a column cannot have null (empty) values. Every record must have a value for this
column.
Usage: Used when a field is required for every record, such as a user’s email address.
Example: Email VARCHAR(100) NOT NULL means every student must have an email address.
UNIQUE
Definition: Ensures that all values in a column are distinct. No two records can have the same value for this
column.
Usage: Used to enforce uniqueness, like in a column for social security numbers or usernames.
Example: Username VARCHAR(50) UNIQUE ensures no two users can have the same username.
PRIMARY KEY
Definition: A combination of NOT NULL and UNIQUE. It uniquely identifies each row in a table and cannot be
null.
Example: StudentID INT PRIMARY KEY means each student will have a unique StudentID that cannot be
duplicated or null.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20),
PRIMARY KEY(ID)
);
Summary
Data Types:
Constraints:
PRIMARY KEY: Unique identifier for each row, combining NOT NULL and UNIQUE.
Managing databases involves creating, selecting, and deleting databases. Here are the essential SQL commands for
these tasks:
1. CREATE DATABASE
Definition: Creates a new database. This command sets up a new database environment where tables, views,
and other objects can be created.
Syntax:
sql
CREATE DATABASE database_name;
Output:
2. USE DATABASE
Definition: Select the database to use for subsequent SQL commands. Once a database is selected, any
operations (such as creating tables or querying data) will be performed on that database.
Syntax:
sql
USE database_name;
3. SHOW DATABASES
Definition: Lists all databases available in the database management system (DBMS). This command helps
you view all existing databases and check their names.
Syntax:
sql
SHOW DATABASES;
Example: Running this command will display a list of all databases, including SchoolDB, if it exists.
4. DROP DATABASE
Definition: Deletes an existing database and all of its contents, including tables, data, and other objects. This
command is irreversible, so be cautious when using it.
Syntax:
sql
DROP DATABASE database_name;
Show Tables, Create Table, Describe Table, Alter Table (add and remove an attribute, add and remove primary key),
Drop Table, Insert, Delete
1. SHOW TABLES
Definition: Lists all the tables in the currently selected database. Useful for viewing existing tables and
verifying their names.
Syntax:
sql
SHOW TABLES;
Example: Running this command will display a list of tables in the selected database.
2. CREATE TABLE
Definition: Creates a new table in the database with specified columns and their data types.
Syntax:
sql
CREATE TABLE table_name ( column1 datatype constraints, column2 datatype constraints, ...);
Example: To create a table named Students with columns StudentID, Name, and DateOfBirth:
sql
CREATE TABLE Students ( StudentID INT PRIMARY KEY, Name VARCHAR(50) NOT NULL, DateOfBirth DATE);
3. DESCRIBE TABLE
Definition: Displays the structure of a table, including column names, data types, and constraints.
Syntax:
sql
DESCRIBE table_name;
4. ALTER TABLE
Definition: Modifies the structure of an existing table, such as adding or removing columns and constraints.
Add an Attribute:
Syntax:
sql
ALTER TABLE table_name
ADD column_name datatype constraints;
Remove an Attribute:
Syntax:
sql
ALTER TABLE table_name
DROP COLUMN column_name;
Example: To remove the Email column from the Students table:
sql
ALTER TABLE Students
DROP COLUMN Email;
Syntax:
sql
ALTER TABLE table_name
ADD PRIMARY KEY (column_name);
Syntax:
sql
ALTER TABLE table_name
DROP PRIMARY KEY;
5. DROP TABLE
Definition: Deletes an existing table and all of its data. This action is irreversible.
Syntax:
sql
DROP TABLE table_name;
6. INSERT
Syntax:
sql
INSERT INTO table_name (column1, column2, ...)VALUES (value1, value2, ...);
7. DELETE
Syntax:
sql
DELETE FROM table_name
WHERE condition;Example: To delete a student with StudentID 1 from the Students table:
sql
DELETE FROM Students
WHERE StudentID = 1;
1. SELECT Statement
The SELECT statement is used to query and retrieve data from a database. It is one of the most commonly used SQL
commands.
Basic Syntax:
sql
SELECT column1, column2, …
FROM table_name
WHERE condition;
Example: To retrieve the Name and DateOfBirth of students from the Students table:
sql
SELECT Name, DateOfBirth
FROM Students;
In this example, we will retrieve all records from the “employee” table where the “emp_city” column does not start
with the letter ‘A’.
Query:
sql
SELECT * FROM employee WHERE emp_city NOT LIKE ‘A%’;
Output:
SELECT Statement
In this example, we will retrieve all records from the “MATHS” table where the value in the “MARKS” column is equal
to 50.
Query:
sql
SELECT * FROM MATHS WHERE MARKS=50;
Output:
SELECT Statement With Conditions
2. Operators in SQL
SQL operators are used to perform operations on data in queries. They can be categorized into mathematical,
relational, and logical operators.
Mathematical Operators
Common Operators:
Relational Operators
Common Operators:
Not Equal To (<> or !=): Checks if two values are not equal.
Less Than or Equal To (<=): Check if a value is less than or equal to another.
Logical Operators
Common Operators:
o Example: SELECT * FROM Students WHERE Grade = ‘A’ AND Age > 18
o Example: SELECT * FROM Customers WHERE Name LIKE ‘J%’; (Finds names starting with ‘J’)
In this example, retrieve all records from the “employee” table where the “emp_city” column is equal to ‘Allahabad’
and the “emp_country” column is equal to ‘India’.
Output:
1. Aliasing
Definition: Aliasing is used to create temporary names for tables or columns in a query to make them more
readable or to simplify complex queries.
Syntax:
sql
SELECT column_name AS alias_name
Example: To create a shorter name for the Students table and a column alias for DateOfBirth:
sql
SELECT Name AS StudentName, DateOfBirth AS DOB
FROM Students AS S;
2. DISTINCT Clause
Definition: The DISTINCT clause removes duplicate rows from the result set, showing only unique values.
Syntax:
sql
SELECT DISTINCT column_name
FROM table_name;
3. WHERE Clause
Definition: The WHERE clause filters records to include only those that meet a specified condition.
Syntax:
sql
SELECT column1, column2, …
FROM table_name
WHERE condition;
4. IN Operator
Definition: The IN operator checks if a value matches any value in a specified list.
Syntax:
sql
SELECT column_name
FROM table_name
Definition: The BETWEEN operator filters records within a specified range (inclusive).
Syntax:
sql
SELECT column_name
FROM table_name
6. ORDER BY Clause
Definition: The ORDER BY clause sorts the result set by one or more columns. You can sort in ascending (default) or
descending order.
Syntax:
sql
SELECT column1, column2, …
FROM table_name
Meaning of null, is null, is not null, like, update command, delete command
Setting a NULL value is appropriate when the actual value is unknown, or when a value is not meaningful.
A NULL value is not equivalent to a value of ZERO if the data type is a number and is not equivalent to spaces
if the data type is a character.
Suppose if any column has a NULL value, then UNIQUE, FOREIGN key, and CHECK constraints will ignore by
SQL.
Use of AND Logical Expression
In general, each NULL value is considered to be different from every other NULL in the database. When a NULL is
involved in a comparison operation, the result is considered to be UNKNOWN. Hence, SQL uses a three-valued logic
with values True, False, and Unknown. It is, therefore, necessary to define the results of three-valued logical
expressions when the logical connectives AND, OR, and NOT are used.
1. Meaning of NULL
Definition: NULL represents the absence of a value or unknown data in a database. It is not the same as an
empty string or zero. It signifies that the value is missing or not applicable.
Example: In a Students table, a Graduation Date column might be NULL if the student hasn’t graduated yet.
2. IS NULL
Definition: The IS NULL condition is used to check if a column contains a NULL value.
Syntax:
sql
SELECT column_name
FROM table_name
3. IS NOT NULL
Definition: The IS NOT NULL condition is used to check if a column does not contain a NULL value.
Syntax:
sql
SELECT column_name
FROM table_name
4. LIKE Operator
Definition: The LIKE operator is used for pattern matching in a WHERE clause. It allows you to search for a specified
pattern in a column.
Syntax:
sql
SELECT column_name
FROM table_name
Pattern Matching:
Examples:
5. UPDATE Command
Syntax:
sql
UPDATE table_name
WHERE condition;
6. DELETE Command
Definition: The DELETE command removes existing records from a table based on a specified condition.
Syntax:
sql
DELETE FROM table_name
WHERE condition;
Aggregate Functions (max, min, avg, sum, count), group by, having clause
1. Aggregate Functions
Aggregate functions perform calculations on a set of values and return a single result. They are often used with the
GROUP BY clause to summarize data.
Syntax:
sql
SELECT MAX(column_name)
FROM table_name;
Syntax:
sql
SELECT MIN(column_name)
FROM table_name;
Syntax:
sql
SELECT AVG(column_name)
FROM table_name;
Syntax:
sql
SELECT SUM(column_name)
FROM table_name;
Syntax:
sql
SELECT COUNT(column_name)
FROM table_name;
2. GROUP BY Clause
Definition: The GROUP BY clause groups rows that have the same values into summary rows. It is commonly
used with aggregate functions to perform operations on each group.
Syntax:
sql
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name;
3. HAVING Clause
Definition: The HAVING clause filters groups of rows based on a specified condition, similar to the WHERE
clause but used for groups.
Syntax:
sql
SELECT column_name, aggregate_function(column_name)
FROM table_name
GROUP BY column_name
HAVING condition;
Example: To find categories where the average price is more than 50:
sql
SELECT Category, AVG(Price) AS AveragePrice
FROM Products
GROUP BY Category
HAVING AVG(Price) > 50;
SQL Joins
Joins are used to combine rows from two or more tables based on a related column. SQL JOIN clause is used to query
and access data from multiple tables by establishing logical relationships between them. It can access data from
multiple tables simultaneously using common key values shared across different tables.
We can use SQL JOIN with multiple tables. It can also be paired with other clauses, the most popular use will be using
JOIN with WHERE clause to filter data retrieval.
Student:
Student
Table
Student Course:
Both these tables are connected by one common key (column) i.e ROLL_NO.
Output:
1. Cartesian Product
Definition: The Cartesian product (also known as a cross join) returns all possible combinations of rows from
two tables. Each row from the first table is paired with every row from the second table.
Syntax:
sql
SELECT *
Example: If Students has 3 rows and Courses has 4 rows, the Cartesian product will produce 12 rows.
sql
SELECT *FROM Students, Courses;
Note: Cartesian products can generate a large number of rows, so use them with caution.
2. Equi-Join
Definition: An equi-join (also known as an inner join) combines rows from two tables based on matching
values in specified columns. It retrieves rows where the specified columns have equal values.
Syntax:
sql
SELECT table1.column1, table2.column2, …
FROM table1
ON table1.common_column = table2.common_column;
Example: To find students and their enrolled courses:
sql
SELECT Students.Name, Courses.CourseName
FROM Students
ON Students.StudentID = Enrollments.StudentID
ON Enrollments.CourseID = Courses.CourseID;
3. Natural Join
Definition: A natural join automatically joins tables based on columns with the same name and data type in
both tables. It selects rows where the values in these common columns are equal.
Syntax:
sql
SELECT *
FROM table1
Example: To automatically join Students and Enrollments on the common column StudentID:
sql
SELECT *FROM Students
NATURAL JOIN Enrollments;
Note: Be careful with natural joins, as they rely on column names and types being identical in both tables,
which might lead to unintended results if there are columns with the same names but different meanings.
Summary
Cartesian Product: Produces all possible combinations of rows from two tables. (SELECT * FROM table1,
table2;)
Equi-Join: Combines rows based on matching column values (INNER JOIN … ON …).
Natural Join: Joins tables based on columns with the same names and data types (NATURAL JOIN).
To interact with an SQL database from Python, you typically use libraries that provide database connectivity and
operations. Here’s a guide on how to connect Python with an SQL database, specifically focusing on popular libraries
like sqlite3, mysql-connector-python, and psycopg2.
SQL
connection with Python
SQLite is a lightweight, disk-based database that’s built into Python’s standard library. It’s great for small to medium-
sized applications.
Steps:
Example:
python
import sqlite3
conn = sqlite3.connect(‘example.db’)
cursor = conn.cursor()
# Create a table
conn.commit()
rows = cursor.fetchall()
print(row)
conn.close()
To connect to a MySQL database, you can use the mysql-connector-python library. You need to install it via pip if you
haven’t already.
Installation:
bash
pip install mysql-connector-python
Example:
python
import mysql.connector
conn = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”yourdatabase”
cursor = conn.cursor()
# Create a table
# Insert a record
cursor.execute(“INSERT INTO students (name, age) VALUES (%s, %s)”, (‘Bob’, 22))
conn.commit()
# Query the database
rows = cursor.fetchall()
print(row)
conn.close()
To connect to a PostgreSQL database, you can use the psycopg2 library. Install it via pip if needed.
Installation:
bash
pip install psycopg2
Example:
python
import psycopg2
conn = psycopg2.connect(
dbname=”yourdatabase”,
user=”yourusername”,
password=”yourpassword”,
host=”localhost”
cursor = conn.cursor()
# Create a table
# Insert a record
cursor.execute(“INSERT INTO students (name, age) VALUES (%s, %s)”, (‘Charlie’, 23))
conn.commit()
rows = cursor.fetchall()
print(row)
# Close the connection
conn.close()
Using a cursor object, you can execute SQL queries to perform operations like inserting, updating, and deleting data
in a database. Here’s how to use the cursor for these operations in Python, with examples for SQLite, MySQL,
and PostgreSQL.
1. Inserting Data
Example:
python
import sqlite3
conn = sqlite3.connect(‘example.db’)
cursor = conn.cursor()
# Insert a record
cursor.execute(“INSERT INTO students (name, age) VALUES (?, ?)”, (‘John Doe’, 25))
conn.commit()
conn.close()
2. Updating Data
Example:
python
import mysql.connector
conn = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”yourdatabase”
cursor = conn.cursor()
# Update a record
cursor.execute(“UPDATE students SET age = %s WHERE name = %s”, (26, ‘John Doe’))
# Commit the changes
conn.commit()
conn.close()
3. Deleting Data
Example:
python
import psycopg2
conn = psycopg2.connect(
dbname=”yourdatabase”,
user=”yourusername”,
password=”yourpassword”,
host=”localhost”
cursor = conn.cursor()
# Delete a record
conn.commit()
conn.close()
CBSE Class 12th Computer Science Unit 3 Notes: Database Management
Display Data by using connect(), cursor(), execute(), commit(), fetchone(), fetchall(), rowcount
When working with SQL databases in Python, you typically use methods like connect(), cursor(), execute(), commit(),
fetchone(), fetchall(), and rowcount to interact with and display data. Here’s how you can use these methods
effectively with examples.
Example:
import sqlite3
conn = sqlite3.connect(‘example.db’)
Definition: Create a cursor object using cursor(). The cursor allows you to execute SQL commands.
Example:
cursor = conn.cursor()
Example:
cursor.execute("SELECT * FROM students")
4. Fetch Data
Methods:
fetchone(): Fetches the next row of a query result set, returning a single sequence or None.
Example:
row = cursor.fetchone()
print(row)
fetchall(): Fetches all (remaining) rows of a query result, returning a list of tuples.
Example:
rows = cursor.fetchall()for row in rows:
print(row)
Definition: Use rowcount to get the number of rows affected by the last operation.
Example:
Python
cursor.execute("DELETE FROM students WHERE age < 20")
print(f"Number of rows deleted: {cursor.rowcount}")
Example:
python
conn.commit()
Example:
python
cursor.close()
conn.close()
Complete Example
Here’s a complete example that demonstrates connecting to a SQLite database, executing a query, fetching data, and
displaying it:
python
import sqlite3
conn = sqlite3.connect(‘example.db’)
# Execute a query
rows = cursor.fetchall()
print(row)
cursor.close()
conn.close()
Creating database connectivity applications in Python involves several key steps. Here’s a comprehensive guide to
help you build applications that connect to, query, and manipulate databases using popular SQL libraries.
Install Required Libraries: Depending on the database you’re working with, you may need to install
specific Python libraries. Here’s how to install some of the most commonly used libraries:
MySQL:
bash
pip install mysql-connector-python
PostgreSQL:
bash
pip install psycopg2
Establishing a connection is the first step in database connectivity. Below are examples for SQLite, MySQL, and
PostgreSQL.
SQLite
import sqlite3
conn = sqlite3.connect(‘mydatabase.db’)
MySQL
import mysql.connector
conn = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”yourdatabase”
PostgreSQL
import psycopg2
conn = psycopg2.connect(
dbname=”yourdatabase”,
user=”yourusername”,
password=”yourpassword”,
host=”localhost”
The cursor object allows you to execute SQL queries and fetch results.
python
cursor = conn.cursor()
You can execute various SQL queries such as creating tables, inserting data, updating records, and more.
Create Table
python
Insert Data
python
cursor.execute(“INSERT INTO students (name, age) VALUES (?, ?)”, (‘Alice’, 22))
Update Data
python
Delete Data
python
5. Fetching Data
Retrieve data from the database using methods like fetchone(), fetchall(), or fetchmany(size).
rows = cursor.fetchall()
print(row)
row = cursor.fetchone()
print(row)
6. Committing Transactions
For operations that modify the database, use commit() to save changes.
python
conn.commit()
python
cursor.close()
conn.close()
Here’s a complete example that demonstrates a simple Python application with database connectivity. This example
uses SQLite for simplicity, but the approach is similar for MySQL and PostgreSQL.
python
import sqlite3
def create_table(conn):
cursor = conn.cursor()
conn.commit()
cursor = conn.cursor()
cursor.execute(“INSERT INTO students (name, age) VALUES (?, ?)”, (name, age))
conn.commit()
def fetch_students(conn):
cursor = conn.cursor()
rows = cursor.fetchall()
print(row)
def main():
conn = sqlite3.connect(‘mydatabase.db’)
# Create table
create_table(conn)
fetch_students(conn)
conn.close()
if __name__ == “__main__”:
main()
When executing SQL queries in Python, you often need to pass parameters to queries. There are different ways to do
this, such as using the %s format specifier or the format() method. It’s important to use the correct approach to
ensure that your queries are both functional and secure.
The %s format specifier is commonly used with libraries like sqlite3, mysql-connector-python, and psycopg2. This
method is generally preferred because it helps prevent SQL injection attacks by automatically escaping special
characters.
python
import sqlite3
conn = sqlite3.connect(‘example.db’)
cursor = conn.cursor()
cursor.execute(“INSERT INTO students (name, age) VALUES (?, ?)”, (‘John Doe’, 25))
conn.commit()
print(cursor.fetchone())
cursor.close()
conn.close()
python
import mysql.connector
conn = mysql.connector.connect(
host=”localhost”,
user=”yourusername”,
password=”yourpassword”,
database=”yourdatabase”
cursor = conn.cursor()
cursor.execute(“INSERT INTO students (name, age) VALUES (%s, %s)”, (‘Jane Smith’, 30))
conn.commit()
print(cursor.fetchone())
cursor.close()
conn.close()
python
import psycopg2
conn = psycopg2.connect(
dbname=”yourdatabase”,
user=”yourusername”,
password=”yourpassword”,
host=”localhost”
)
cursor = conn.cursor()
cursor.execute(“INSERT INTO students (name, age) VALUES (%s, %s)”, (‘Alice Johnson’, 28))
conn.commit()
print(cursor.fetchone())
cursor.close()
conn.close()
While you can use the format() method to construct queries, it is generally not recommended due to security
concerns like SQL injection. Direct string interpolation should be avoided in favor of parameterized queries.
python
import sqlite3
conn = sqlite3.connect(‘example.db’)
cursor = conn.cursor()
age = 25
conn.commit()
print(cursor.fetchone())
cursor.close()
conn.close()
Summary
%s Format Specifier: Preferred method for parameterized queries. It ensures proper escaping of parameters,
thus helping to prevent SQL injection. Use ? for SQLite and %s for MySQL and PostgreSQL.
format() Method: While possible, it is not recommended for constructing SQL queries due to security risks.
Directly inserting user inputs into queries can make your application vulnerable to SQL injection attacks.