12 Computer Science Unit 3
12 Computer Science Unit 3
Table of Content
Database Concepts
Relational Data Model
Keys (candidate key, primary key, alternate key, foreign key)
Structured Query Language
Interface of Python with an SQL Database
CBSE Class 12th Computer Science Unit III Notes: Marks Distribution
Database Concepts
Introduction to Database Concepts and Their Need
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).
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.
Data Integrity:
Need: Ensures that data is accurate, consistent, and reliable.
Benefit: Minimizes errors and maintains the quality of data over time.
Data Security:
Need: Protects sensitive data from unauthorized access and breaches.
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.
Benefit: Facilitates teamwork and collaboration in real-time.
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.
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.
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:
Must be unique for each row.
Cannot contain null values.
Example: In a Student table, StudentID and Email might both be candidate keys if each is
unique for every student.
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:
Uniquely identifies each record in the table.
Cannot have null values.
Each table can have only one primary key.
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:
Each alternate key could potentially serve as a primary key.
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.
Can contain duplicate values and nulls if allowed.
Example: In an Enrollments table, StudentID might be a foreign key that refers to the
StudentID primary key in the Students table.
ALTER: Used to modify existing database objects, such as adding or deleting columns in a
table.
o Example: ALTER TABLE Students ADD Email VARCHAR(100)
TRUNCATE: Used to remove all records from a table without deleting the table structure.
o Example: TRUNCATE TABLE Students;
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)
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.
Usage: Commonly used for numerical data like IDs or counts.
Example: INT can store values like 1, -42, or 1000.
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.
Example: FLOAT can store values like 3.14 or -0.001.
DATE
Definition: A date value in the format YYYY-MM-DD. It stores calendar dates.
Usage: Used for storing dates of events, birthdays, or deadlines.
Example: DATE can store values like 2024-08-01.
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.
CREATE TABLE sample_table
(
column1 data_type(size) constraint_name,
column2 data_type(size) constraint_name,
column3 data_type(size) constraint_name,
....
);
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.
CREATE TABLE Student
(
ID int(6) NOT NULL,
NAME varchar(10) NOT NULL,
ADDRESS varchar(20)
);
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.
CREATE TABLE Student
(
ID int(6) NOT NULL UNIQUE,
NAME varchar(10),
ADDRESS varchar(20)
);
PRIMARY KEY
Definition: A combination of NOT NULL and UNIQUE. It uniquely identifies each row in a
table and cannot be null.
Usage: Used to uniquely identify records, such as in an ID column or a student number.
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:
CHAR(n): Fixed-length text.
VARCHAR(n): Variable-length text.
INT: Whole numbers.
FLOAT: Decimal numbers.
DATE: Calendar dates.
Constraints:
NOT NULL: Column must have a value.
UNIQUE: Values in the column must be distinct.
PRIMARY KEY: Unique identifier for each row, combining NOT NULL and UNIQUE.
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;
Example: To create a database named SchoolDB, you would use:
sql
CREATE DATABASE GeeksForGeeks;
Output:
Creating a new database
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;
Example: To switch to the SchoolDB database, you would use:
sql
USE SchoolDB;
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.
Database successfully created
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;
Example: To delete the SchoolDB database, you would use:
sql
DROP DATABASE SchoolDB;
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;
Example: To view the structure of the Students table:
sql
DESCRIBE Students;
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;
Example: To add an Email column to the Students table:
sq
ALTER TABLE Students
ADD Email VARCHAR(100);
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;
5. DROP TABLE
Definition: Deletes an existing table and all of its data. This action is irreversible.
Syntax:
sql
DROP TABLE table_name;
Example: To delete the Students table:
sql
DROP TABLE Students;
6. INSERT
Definition: Adds new rows of data into a table.
Syntax:
sql
INSERT INTO table_name (column1, column2, ...)VALUES (value1, value2,
...);
Example: To insert a new student into the Students table:
sql
INSERT INTO Students (StudentID, Name, DateOfBirth)VALUES (1, 'Alice
Smith', '2005-05-15');
7. DELETE
Definition: Removes existing rows from a table based on a specified condition.
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;
Query:
sql
SELECT * FROM employee WHERE emp_city NOT LIKE 'A%';
Output:
SELECT Statement
Query:
sql
SELECT * FROM MATHS WHERE MARKS=50;
Output:
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
Definition: Used to perform arithmetic operations.
Common Operators:
Addition (+): Adds two values.
o Example: SELECT Price + Tax AS Total FROM Products
Relational Operators
Definition: Used to compare values and return a boolean result.
Common Operators:
Equal To (=): Checks if two values are equal.
o Example: SELECT * FROM Students WHERE StudentID = 1
Not Equal To (<> or !=): Checks if two values are not equal.
o Example: SELECT * FROM Students WHERE Status <> 'Inactive'
Greater Than or Equal To (>=): Checks if a value is greater than or equal to another.
o Example: SELECT * FROM Products WHERE Price >= 100
Less Than or Equal To (<=): Check if a value is less than or equal to another.
o Example: SELECT * FROM Products WHERE Price <= 50
Logical Operators
Definition: Used to combine multiple conditions in queries.
Common Operators:
AND: Returns true if both conditions are true.
o Example: SELECT * FROM Students WHERE Grade = 'A' AND Age > 18
Output:
Use of Logical Operator
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;
Example: To find unique Grade values in the Students table:
sql
SELECT DISTINCT Grade
FROM Students;
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;
Example: To select students older than 18:
sql
SELECT Name, Age
FROM Students
WHERE Age > 18;
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
WHERE column_name IN (value1, value2, ...);
Example: To select students with grades 'A' or 'B':
sql
SELECT Name
FROM Students
WHERE Grade IN ('A', 'B');
5. BETWEEN Operator
Definition: The BETWEEN operator filters records within a specified range (inclusive).
Syntax:
sql
SELECT column_name
FROM table_name
WHERE column_name BETWEEN value1 AND value2;
Example: To find products with prices between 10 and 50:
sql
SELECT ProductName
FROM Products
WHERE Price BETWEEN 10 AND 50;
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
ORDER BY column_name [ASC|DESC];
Example: To select students and sort them by age in ascending order:
sql
SELECT Name, Age
FROM Students
ORDER BY Age ASC;
Meaning of null, is null, is not null, like, update command, delete command
Principles of NULL values
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.
A NULL value can be inserted into columns of any data type.
A NULL value will evaluate NULL in any expression.
Suppose if any column has a NULL value, then UNIQUE, FOREIGN Key, and CHECK
constraints will ignore by SQL.
Use of AND Logical Expression
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
WHERE column_name IS NULL;
Example: To find students without a specified GraduationDate:
sql
SELECT NameFROM Students
WHERE GraduationDate IS NULL;
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
WHERE column_name IS NOT NULL;
Example: To find students with a specified GraduationDate:
sql
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
WHERE column_name LIKE pattern;
Pattern Matching:
%: Represents zero or more characters.
_: Represents a single character.
Examples:
To find names starting with 'J':
sql
SELECT NameFROM Students
WHERE Name LIKE 'J%';
To find names with exactly 4 characters:
sql
SELECT NameFROM Students
WHERE Name LIKE '____';
5. UPDATE Command
Definition: The UPDATE command is used to modify existing records in a table.
Syntax:
sql
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Example: To update the Grade of a student with StudentID 1:
sql
UPDATE StudentsSET Grade = 'A'
WHERE StudentID = 1;
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;
Example: To delete a student with StudentID 1:
sql
DELETE FROM Students
WHERE StudentID = 1;
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.
MAX( ): Returns the maximum value in a set.
Syntax:
sql
SELECT MAX(column_name)
FROM table_name;
Example: To find the highest price in the Products table:
sql
Copy code
SELECT MAX(Price) AS MaxPrice
FROM Products;
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;
Example: To find the average price of products for each category:
sql
SELECT Category, AVG(Price) AS AveragePrice
FROM Products
GROUP BY Category;
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.
Stude
nt Table
Student Course:
Student Course Table
Both these tables are connected by one common key (column) i.e ROLL_NO.
We can perform a JOIN operation using the given SQL query:
SELECT s.roll_no, s.name, s.address, s.phone, s.age, sc.course_id
FROM Student s
JOIN StudentCourse sc ON s.roll_no = sc.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 *
FROM table1, table2;
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
INNER JOIN table2
ON table1.common_column = table2.common_column;
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
NATURAL JOIN table2;
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).
Example:
python
import sqlite3
# Connect to the database (or create it if it doesn't exist)
conn = sqlite3.connect('example.db')
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES ('Alice', 21)")
Example:
python
import mysql.connector
# Connect to the MySQL database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INT AUTO_INCREMENT PRIMARY KEY, name VARCHAR(255), age
INT)''')
# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Bob', 22))
Example:
python
import psycopg2
# Connect to the PostgreSQL database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
# Create a table
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id SERIAL PRIMARY KEY, name VARCHAR(100), age INTEGER)''')
# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (%s, %s)", ('Charlie', 23))
1. Inserting Data
Definition: Insert new records into a table.
Example:
python
import sqlite3
#Connect to the database
conn = sqlite3.connect('example.db')
cursor = conn.cursor()
# Insert a record
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('John Doe', 25))
2. Updating Data
Definition: Modify existing records in a table .
Example:
python
import mysql.connector
# Connect to the database
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'))
3. Deleting Data
Definition: Remove records from a table .
Example:
python
import psycopg2
# Connect to the database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
cursor = conn.cursor( )
# Delete a record
cursor.execute("DELETE FROM students WHERE name = %s", ('John Doe',))
Example:
import sqlite3
# Connect to the SQLite database
conn = sqlite3.connect('example.db')
4. Fetch Data
Definition: Retrieve data from the executed query.
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)
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
# Connect to the SQLite database
conn = sqlite3.connect('example.db')
# Execute a query
cursor.execute("SELECT * FROM students")
SQLite
import sqlite3
# Connect to an SQLite database (or create it if it doesn't exist)
conn = sqlite3.connect('mydatabase.db')
MySQL
import mysql.connector
# Connect to a MySQL database
conn = mysql.connector.connect(
host="localhost",
user="yourusername",
password="yourpassword",
database="yourdatabase"
)
PostgreSQL
import psycopg2
# Connect to a PostgreSQL database
conn = psycopg2.connect(
dbname="yourdatabase",
user="yourusername",
password="yourpassword",
host="localhost"
)
Create Table
python
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
Insert Data
python
cursor.execute("INSERT INTO students (name, age) VALUES (?, ?)", ('Alice', 22))
Update Data
python
cursor.execute("UPDATE students SET age = ? WHERE name = ?", (23, 'Alice'))
Delete Data
python
cursor.execute("DELETE FROM students WHERE name = ?", ('Alice',))
5. Fetching Data
Retrieve data from the database using methods like fetchone( ), fetchall( ), or fetchmany(size).
6. Committing Transactions
For operations that modify the database, use commit( ) to save changes.
python
conn.commit( )
python
import sqlite3
def create_table(conn):
cursor = conn.cursor( )
cursor.execute('''CREATE TABLE IF NOT EXISTS students
(id INTEGER PRIMARY KEY, name TEXT, age INTEGER)''')
conn.commit( )
def fetch_students(conn):
cursor = conn.cursor( )
cursor.execute("SELECT * FROM students")
rows = cursor.fetchall( )
for row in rows:
print(row)
def main( ):
# Create table
create_table(conn)
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.
CBSE Class 12th Computer Science Unit III Notes: Marks Distribution
Here is the complete marks distribution of computer science class 12th with marks distribution
are as follow:
Topic Marks