Unit-IV
Database Connectivity with MySql Introduction to RDBMS, Connection with MySql
Database, Performing basic database operation (DML) (Insert, Delete, Update,
Select).
Topic 1: Introduction to RDBMS (Relational Database Management System)
1. Introduction
A database is a collection of related data that can be easily accessed, managed, and
updated.
For example, a college database may contain data about students, teachers, subjects,
and fees.
To efficiently store and manage such large amounts of information, we use database
management systems.
A Database Management System (DBMS) is software that allows users to create, store,
and manage data systematically.
Examples of DBMS include MS Access, dBase, and FoxPro.
However, traditional DBMS systems store data in files and do not support relationships
between data items. To overcome this limitation, a more advanced system known as
RDBMS (Relational Database Management System) was developed.
2. Definition of RDBMS
An RDBMS (Relational Database Management System) is a type of DBMS that stores
data in the form of tables (relations) consisting of rows and columns, and allows data to
be related to one another through keys.
In RDBMS:
• Data is represented in tabular form.
• Each table has a unique name.
• Relationships can be established between tables.
• Data manipulation is done using SQL (Structured Query Language).
3. Structure of an RDBMS Table
A table is the basic structure used to store data in an RDBMS.
Each table consists of rows (records) and columns (fields or attributes).
Example:
Student Table
Roll_No Name Age Course
101 Rohan 20 BCA
102 Suman 21 MCA
103 Deepika 22 [Link]
• Here, Roll_No is the Primary Key, which uniquely identifies each student.
• Name, Age, and Course are attributes of the student.
• Each row represents a single student’s data.
4. Important Terminologies Used in RDBMS
Term Description
Table A collection of related data in rows and columns.
Row (Record or A single entry or record in a table.
Tuple)
Column (Field or Represents a specific property of the data.
Attribute)
Primary Key A unique column used to identify each record in a table.
Foreign Key A column that refers to the primary key in another table to
create relationships.
Schema The logical design or structure of a database (tables,
columns, data types, relationships).
Relationship A link between two or more tables based on common fields.
5. Features of RDBMS
1. Data Stored in Tables:
Data is stored in tabular form consisting of rows and columns.
2. Relationships Between Tables:
RDBMS allows relationships between tables using primary and foreign keys.
3. Data Integrity:
Ensures data accuracy and consistency through constraints like Primary Key,
Foreign Key, and Not Null.
4. SQL Support:
RDBMS supports SQL for creating, modifying, and retrieving data.
5. Data Security:
User permissions and roles ensure that only authorized users can access or
modify data.
6. Data Independence:
Changes in data structure do not affect the overall application.
7. Reduced Redundancy:
Normalization techniques are used to minimize duplication of data.
8. Multi-user Access:
Multiple users can access and modify data concurrently.
9. Backup and Recovery:
RDBMS systems provide automatic data backup and recovery options.
6. Advantages of RDBMS
1. Data Accuracy and Integrity:
Ensures that data entered into the database is correct and consistent.
2. Reduced Data Redundancy:
Prevents duplication of data by organizing information into separate related
tables.
3. Data Security:
Provides access control using usernames and passwords.
4. Data Consistency:
Changes made in one place automatically reflect everywhere.
5. Easy Data Retrieval:
Data can be easily retrieved using SQL queries.
6. Data Sharing:
Multiple users can access the same data simultaneously.
7. Relationship Management:
Data in different tables can be linked and used together.
7. Examples of RDBMS Software
Software Name Developer Description
MySQL Oracle Corporation Open-source RDBMS widely used for
web and server applications.
Oracle Oracle Corporation Enterprise-level database with
Database advanced performance features.
Microsoft SQL Microsoft Secure and scalable database system
Server used in enterprises.
PostgreSQL PostgreSQL Global Open-source RDBMS with strong
Development Group reliability and ACID compliance.
SQLite Public Domain Lightweight, file-based database used
in mobile and embedded systems.
8. Relationship Between Tables
Relationships allow data in different tables to be linked together using keys.
Example:
Table 1: Students
Roll_No Name Age
101 Rohan 20
102 Suman 21
Table 2: Courses
Course_ID Roll_No Course_Name
C01 101 BCA
C02 102 MCA
Here, Roll_No is the Foreign Key in the Courses table that refers to the Primary Key in the
Students table.
This creates a relationship between both tables.
9. Difference Between DBMS and RDBMS
Feature DBMS RDBMS
Data Storage Data stored in files Data stored in tables
Relationships Not supported Supported using keys
Data Redundancy High Low due to normalization
Normalization Not supported Supported
Data Integrity Not guaranteed Ensured through constraints
Multi-user Access Limited Supported
Example MS Access, dBase MySQL, Oracle, SQL Server
Examples of Popular RDBMS
1. MySQL: An open-source RDBMS known for its speed and reliability.
2. PostgreSQL: An advanced open-source RDBMS with a strong emphasis on
extensibility and standards compliance.
3. Oracle Database: A multi-model RDBMS known for its robustness and
enterprise features.
4. Microsoft SQL Server: A relational database management system developed by
Microsoft, known for its integration with other Microsoft products.
5. SQLite: A self-contained, high-reliability, embedded, full-featured, public-
domain, SQL database engine.
Topic 2: Connection with MySQL Database
1. Introduction
When we develop a program or web application, it often needs to store, retrieve, and
manipulate data.
To perform these operations, the program must connect to a database system like
MySQL.
This process is known as Database Connectivity.
In simple terms, Database Connectivity means establishing a link between a
programming language (like Python, Java, or PHP) and a MySQL Database Server so that
data can be inserted, updated, deleted, or retrieved.
2. What is MySQL?
• MySQL is an open-source Relational Database Management System (RDBMS)
developed by Oracle Corporation.
• It stores data in tables and uses SQL (Structured Query Language) for data
manipulation.
• MySQL is widely used in web applications like WordPress, Facebook, and
YouTube.
3. MySQL Architecture Overview
MySQL follows a Client-Server Architecture, which means:
• Client: The program or application that sends requests (like insert, update,
select).
• Server: The MySQL Database Server that processes these requests and returns
the result.
Working Process:
1. The client (e.g., Python, PHP, or Java) sends an SQL query.
2. The MySQL server executes the query.
3. The server sends back the result to the client.
4. Steps to Connect with MySQL Database
Connecting to MySQL involves a few systematic steps.
Below are the general steps followed in all programming languages (Python, PHP, Java,
etc.):
Step 1: Load the MySQL Driver
A driver or connector is software that allows the program to communicate with the
MySQL server.
For example:
• In Python → [Link]
• In Java → [Link]
• In PHP → mysqli_connect()
Step 2: Establish the Connection
You must specify the following parameters to connect:
• Host name: Server address where MySQL is running (usually "localhost" for local
machine)
• Username: MySQL user name (default is "root")
• Password: Password for the MySQL account
• Database name: The database to which connection is required
Step 3: Create a Cursor or Statement Object
After the connection is established, you must create a cursor or statement object to
execute SQL queries.
In PHP (mysqli) you use the connection object to execute queries, or use prepared
statements.
• Cursor (Python) → Allows you to execute SQL queries and fetch results.
• Statement (Java) → Used to execute queries in Java.
Step 4: Execute SQL Queries
Once the cursor or statement is created, you can execute SQL queries such as:
• INSERT
• UPDATE
• DELETE
• SELECT
Step 5: Process the Results
After executing a query, you can:
• View the output.
• Store it in variables.
• Display it to the user.
Step 6: Close the Connection
When all database operations are completed, the connection should be closed using a
command like [Link]().
This is important to release memory and system resources.
Example: Connecting MySQL with PHP (mysqli procedural / prepared
statements)
Step 1: Ensure mysqli extension is enabled (default in PHP).
Step 2: Create a Connection
<?php
$host = "localhost";
$user = "root";
$password = "yourpassword";
$database = "studentdb";
/* Create connection */
$conn = mysqli_connect($host, $user, $password, $database);
/* Check connection */
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connection established successfully!";
?>
Explanation:
• mysqli_connect() establishes a connection with the database.
• Parameters: host → MySQL server location (usually "localhost")
user → MySQL username
password → Account password
database → Name of the database you want to connect to
Step 3: Create a Table (if not exists)
<?php
// Assuming $conn is the mysqli connection from previous example
$sql = "CREATE TABLE IF NOT EXISTS student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT
)";
if (mysqli_query($conn, $sql)) {
echo "Table created successfully!";
} else {
echo "Error creating table: " . mysqli_error($conn);
}
?>
Explanation:
• mysqli_query() executes the SQL command on the MySQL server.
Step 4: Insert Data (using prepared statement to avoid SQL injection)
<?php
// Prepare an insert statement
$stmt = mysqli_prepare($conn, "INSERT INTO student (id, name, age) VALUES
(?, ?, ?)");
$id = 1;
$name = "Hardeep";
$age = 22;
/* bind parameters: 'i' => integer, 's' => string */
mysqli_stmt_bind_param($stmt, "isi", $id, $name, $age);
/* execute the statement */
if (mysqli_stmt_execute($stmt)) {
echo "Record inserted successfully!";
} else {
echo "Error inserting record: " . mysqli_stmt_error($stmt);
}
/* close statement */
mysqli_stmt_close($stmt);
?>
Explanation:
• Prepared statements are safer and prevent SQL injection.
• mysqli_stmt_bind_param() binds variables to the parameter markers.
Step 5: Fetch Data (SELECT)
<?php
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
if ($result) {
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_assoc($result)) {
// $row is an associative array of column => value
echo "ID: " . $row['id'] . " Name: " . $row['name'] . " Age: "
. $row['age'] . "\n";
}
} else {
echo "No records found.";
}
} else {
echo "SELECT error: " . mysqli_error($conn);
}
?>
Explanation:
• mysqli_fetch_assoc() fetches a result row as an associative array.
Step 6: Close the Connection
<?php
mysqli_close($conn);
echo "Database connection closed.";
?>
6. General Syntax for Connection (in any Language)
Languag Method or Function Used Example
e
Python [Link]() Connects
using Python
module
PHP mysqli_connect("localhost", "root", "password", Used for
"db_name") web
developmen
t
Java [Link]("jdbc:mysql://localhost/db Uses JDBC
", "root", "password") driver
C# MySqlConnection conn = new Uses .NET
MySqlConnection(connectionString); MySQL
library
7. Common Connection Errors and Solutions
Error Message Cause Solution
Access denied for user Wrong username or Verify login credentials
'root' password
Unknown database Database name is Check if database exists
incorrect
Can't connect to MySQL Server not running Start MySQL service
server
ModuleNotFoundError Connector not Install using pip install mysql-
installed connector-python
8. Advantages of MySQL Connectivity
1. Allows applications to interact directly with databases.
2. Provides dynamic data access in real-time.
3. Reduces manual data entry work.
4. Enables data-driven websites and applications.
5. Improves data management and integrity.
Topic 3: Performing Basic Database Operations (DML)
1. Introduction
After establishing a connection between a program (such as Python, Java, or PHP) and a
MySQL database, we can perform operations on the stored data.
These operations include inserting new data, modifying existing data, removing data,
and retrieving data from tables.
Such operations are done using DML commands (Data Manipulation Language) in
SQL.
2. What is DML?
DML (Data Manipulation Language) is a subset of SQL commands that are used to
manipulate data stored in database tables.
Common DML Commands
Command Description
INSERT Adds new records (rows) to a table
UPDATE Modifies existing data in a table
DELETE Removes records from a table
SELECT Retrieves data from one or more tables
DML commands are executed after establishing a connection with the database.
When a DML command changes the data (Insert, Update, Delete), we must use the
COMMIT command to save the changes permanently.
3. The INSERT Command
Purpose:
To add one or more new records (rows) into a table.
Syntax:
INSERT INTO table_name (column1, column2, column3, ...)
VALUES (value1, value2, value3, ...);
Example:
INSERT INTO student (id, name, age, course)
VALUES (101, 'Hardeep', 22, 'BCA');
This query will insert a new record into the student table.
PHP Example (mysqli prepared statement):
<?php
// Assuming $conn is existing mysqli connection
$stmt = mysqli_prepare($conn, "INSERT INTO student (id, name, age, course) VALUES
(?, ?, ?, ?)");
$id = 102;
$name = "Gurjeet";
$age = 25;
$course = "MCA";
mysqli_stmt_bind_param($stmt, "isis", $id, $name, $age, $course);
if (mysqli_stmt_execute($stmt)) {
echo "Record inserted successfully!";
} else {
echo "Insert error: " . mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
?>
Explanation:
• INSERT INTO is used to add new records.
• Use mysqli_commit() if you have disabled autocommit and want to commit a
transaction.
4. The SELECT Command
Purpose:
To retrieve data from one or more tables.
Syntax:
SELECT column1, column2, ...
FROM table_name
WHERE condition;
Example:
SELECT * FROM student;
This retrieves all columns and all rows from the student table.
Example with Condition:
SELECT name, age FROM student WHERE course = 'BCA';
Php Example:
<?php
$sql = "SELECT * FROM student";
$result = mysqli_query($conn, $sql);
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'] . " " . $row['name'] . " " . $row['age'] . " " . $row['course'] . "\n";
mysqli_free_result($result);
} else {
echo "SELECT error: " . mysqli_error($conn);
?>
Explanation:
• SELECT * → Fetches all columns.
• mysqli_fetch_assoc() → Returns each row as an associative array.
5. The UPDATE Command
Purpose:
To modify existing data in one or more rows of a table.
Syntax:
UPDATE table_name
SET column1 = value1, column2 = value2, ...
WHERE condition;
Note: Always use a WHERE clause, otherwise all records in the table will be updated.
Example:
UPDATE student
SET age = 23
WHERE id = 101;
This updates the age of the student whose id = 101.
Php Example:
<?php
$stmt = mysqli_prepare($conn, "UPDATE student SET age = ? WHERE id = ?");
$newAge = 24;
$idToUpdate = 102;
mysqli_stmt_bind_param($stmt, "ii", $newAge, $idToUpdate);
if (mysqli_stmt_execute($stmt)) {
echo "Record updated successfully!";
} else {
echo "Update error: " . mysqli_stmt_error($stmt);
mysqli_stmt_close($stmt);
?>
Explanation:
• UPDATE → Modifies existing data.
• WHERE → Specifies which record to update.
• commit() → Saves the changes to the database.
6. The DELETE Command
Purpose:
To remove one or more records from a table.
Syntax:
DELETE FROM table_name WHERE condition;
Note:
If you omit the WHERE clause, all rows will be deleted from the table.
Example:
DELETE FROM student WHERE id = 101;
This command deletes the student record with id = 101.
php Example:
<?php
$stmt = mysqli_prepare($conn, "DELETE FROM student WHERE id = ?");
$idToDelete = 102;
mysqli_stmt_bind_param($stmt, "i", $idToDelete);
if (mysqli_stmt_execute($stmt)) {
echo "Record deleted successfully!";
} else {
echo "Delete error: " . mysqli_stmt_error($stmt);
}
mysqli_stmt_close($stmt);
?>
Explanation:
• DELETE FROM removes data.
• commit() confirms the deletion.
7. Commit and Rollback
• COMMIT:
Saves the changes made by DML commands permanently to the database.
• COMMIT;
• ROLLBACK:
Cancels or undoes the changes made after the last COMMIT command.
• ROLLBACK;
These are important in transactional databases where operations can be grouped
together for safety and consistency.
8. Summary of DML Commands
Command Operation Description Example
INSERT Add data Inserts new records INSERT INTO student VALUES
into a table (1,'Aman',22,'BCA');
SELECT Retrieve Fetches data from a SELECT * FROM student;
data table
UPDATE Modify data Changes existing data UPDATE student SET age=23
in a table WHERE id=1;
DELETE Remove Deletes existing DELETE FROM student WHERE
data records id=1;
10. Advantages of DML Operations
1. Provides flexibility to handle data in real-time.
2. Allows easy data entry, correction, and deletion.
3. Helps in managing large datasets through SQL queries.
4. Enables automation of data operations in applications.
5. Ensures accuracy and consistency through transaction control.
Example Program (Complete PHP Script demonstrating DML operations)
<?php
$host = "localhost";
$user = "root";
$password = "yourpassword";
$database = "studentdb";
/* Connect */
$conn = mysqli_connect($host, $user, $password, $database);
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
/* Create table if not exists */
$sqlCreate = "CREATE TABLE IF NOT EXISTS student (
id INT PRIMARY KEY,
name VARCHAR(50),
age INT,
course VARCHAR(50)
)";
mysqli_query($conn, $sqlCreate);
/* Start transaction */
mysqli_autocommit($conn, false);
try {
/* INSERT */
$stmt = mysqli_prepare($conn, "INSERT INTO student (id, name, age,
course) VALUES (?, ?, ?, ?)");
$id = 103;
$name = "Simran";
$age = 21;
$course = "BBA";
mysqli_stmt_bind_param($stmt, "isis", $id, $name, $age, $course);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
/* UPDATE */
$stmt = mysqli_prepare($conn, "UPDATE student SET age = ? WHERE id =
?");
$newAge = 22;
$idUpd = 103;
mysqli_stmt_bind_param($stmt, "ii", $newAge, $idUpd);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
/* SELECT */
$result = mysqli_query($conn, "SELECT * FROM student");
if ($result) {
while ($row = mysqli_fetch_assoc($result)) {
echo $row['id'] . " " . $row['name'] . " " . $row['age'] . " "
. $row['course'] . "\n";
}
mysqli_free_result($result);
}
/* DELETE */
$stmt = mysqli_prepare($conn, "DELETE FROM student WHERE id = ?");
$idDel = 103;
mysqli_stmt_bind_param($stmt, "i", $idDel);
mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);
/* Commit transaction */
mysqli_commit($conn);
echo "All operations completed and committed successfully.";
} catch (Exception $e) {
/* Rollback on error */
mysqli_rollback($conn);
echo "Transaction failed and rolled back: " . $e->getMessage();
}
/* Turn autocommit back on */
mysqli_autocommit($conn, true);
/* Close connection */
mysqli_close($conn);
?>
6.