"Databases"
π· What is a Database?
A database is an organized collection of data that is stored electronically and can be accessed, managed, and updated efficiently.
π· Purpose of a Database
- Store large amounts of data systematically.
- Retrieve data quickly and accurately.
- Manage data with relationships (like between customers and orders).
- Maintain integrity and consistency of data.
- Enable multi-user access with security controls.
π· Types of Databases
| Type | Description | Example |
|---|---|---|
| Relational | Stores data in tables with rows and columns | SQL Server, MySQL, Oracle |
| NoSQL | Stores unstructured or semi-structured data | MongoDB, Cassandra |
| In-Memory | Data stored in RAM for fast access | Redis |
| Cloud-based | Databases hosted on cloud platforms | AWS RDS, Azure SQL Database |
π· Key Components of a Relational Database
| Component | Description |
|---|---|
| Table | A set of rows and columns (like an Excel sheet) |
| Record (Row) | A single data entry in a table |
| Field (Column) | Represents one attribute of data (e.g., Name, Age) |
| Primary Key | Uniquely identifies each record in a table |
| Foreign Key | Links one table to another (for relationships) |
π· Common Database Terms
- SQL (Structured Query Language): Used to query and manipulate data.
-
CRUD Operations:
-
Create: Insert new records.
- Read: Retrieve data.
- Update: Modify existing data.
- Delete: Remove records.
- Normalization: Organizing data to reduce redundancy.
π· How .NET Interacts with Databases
- .NET applications use ADO.NET to connect to databases.
-
Commonly used databases with .NET:
-
Microsoft SQL Server
- SQLite
- MySQL
- Oracle
π· Example Table: Students
| StudentID (PK) | Name | Age | Course |
|---|---|---|---|
| 1 | Rahul | 20 | BCA |
| 2 | Priya | 21 | B.Sc. IT |
π· Benefits of Using Databases in Applications
- Centralized data storage
- Improved performance and security
- Easy backup and recovery
- Data sharing among multiple users
β Summary
| Feature | Description |
|---|---|
| Definition | Structured data storage system |
| Example Systems | SQL Server, MySQL, MongoDB |
| Core Operations | CRUD (Create, Read, Update, Delete) |
| .NET Integration | Via ADO.NET or Entity Framework |
"Database Transaction"
π· What is a Database Transaction?
A database transaction is a sequence of one or more SQL operations that are executed as a single unit of work.
- All operations in a transaction must either complete successfully together (commit) or fail together (rollback).
- A transaction ensures data consistency, accuracy, and integrity.
π· Properties of Transactions β ACID
| Property | Description |
|---|---|
| A β Atomicity | All operations in a transaction are treated as a single unit. Either all succeed or none are applied. |
| C β Consistency | The database moves from one valid state to another after a successful transaction. |
| I β Isolation | Transactions are independent and do not interfere with each other. |
| D β Durability | Once a transaction is committed, changes are permanent even in case of a system failure. |
π· Example Scenario
Imagine transferring βΉ1000 from Account A to Account B:
- Subtract βΉ1000 from Account A.
- Add βΉ1000 to Account B.
If only the first step happens and the second fails β the money is lost. Using a transaction, both steps will succeed or both will fail.
π· Transaction in SQL (Basic Syntax)
BEGIN TRANSACTION;
UPDATE Accounts SET Balance = Balance - 1000 WHERE AccountID = 'A';
UPDATE Accounts SET Balance = Balance + 1000 WHERE AccountID = 'B';
COMMIT;
If there's an error:
ROLLBACK;
π· Using Transactions in ADO.NET (VB.NET Example)
Dim con As New SqlConnection("Your_Connection_String")
con.Open()
Dim transaction As SqlTransaction = con.BeginTransaction()
Dim cmd As New SqlCommand()
cmd.Connection = con
cmd.Transaction = transaction
Try
' First query
cmd.CommandText = "UPDATE Accounts SET Balance = Balance - 1000 WHERE AccountID = 'A'"
cmd.ExecuteNonQuery()
' Second query
cmd.CommandText = "UPDATE Accounts SET Balance = Balance + 1000 WHERE AccountID = 'B'"
cmd.ExecuteNonQuery()
' Commit if both succeed
transaction.Commit()
MessageBox.Show("Transaction Successful")
Catch ex As Exception
' Rollback if error occurs
transaction.Rollback()
MessageBox.Show("Transaction Failed: " & ex.Message)
Finally
con.Close()
End Try
π· Benefits of Using Transactions
- Ensures data accuracy and reliability
- Protects against partial updates or system crashes
- Maintains business rules and logic
β Summary
| Feature | Description |
|---|---|
| Transaction | Group of SQL statements that run as one unit |
| ACID Properties | Guarantees integrity and reliability of data |
| ADO.NET Usage | Begin, Commit, and Rollback via SqlTransaction |
| Real-Life Use Cases | Bank transfers, order processing, reservation systems |
"ADO.NET"
π· What is ADO.NET?
ADO.NET (ActiveX Data Objects for .NET) is a set of classes in the .NET Framework used to interact with databases and other data sources like XML.
- It is part of the System.Data namespace.
- Allows your .NET applications to connect, retrieve, insert, update, and delete data from a database.
- ADO.NET supports both connected and disconnected data access models.
π· Key Features of ADO.NET
| Feature | Description |
|---|---|
| Data Access | Provides access to SQL Server, Oracle, MySQL, XML, etc. |
| Disconnected Architecture | Uses DataSet to work with data offline (not constantly connected) |
| Scalability | Efficient for large-scale enterprise applications |
| Performance | Uses optimized data providers and minimal memory usage |
| Interoperability | Can work with XML and Web Services |
π· ADO.NET Architecture
ADO.NET has two main components:
-
Connected Architecture
-
Works directly with the database using a Connection.
-
Uses Command, DataReader to execute SQL queries and retrieve results.
-
Disconnected Architecture
-
Uses DataSet, DataTable, DataAdapter.
- Data is fetched and stored in memory, and the connection is closed.
- Useful for minimizing open database connections.
π· Key ADO.NET Objects
| Object | Description |
|---|---|
| Connection | Establishes a link between the application and the database. |
| Command | Executes SQL queries (SELECT, INSERT, UPDATE, DELETE). |
| DataReader | Reads data in a fast, forward-only, read-only way (connected). |
| DataAdapter | Fills data into a DataSet (disconnected mode). |
| DataSet | In-memory representation of data (tables, rows, relations). |
| DataTable | Represents a single table of in-memory data. |
| SqlTransaction | Manages transactions (commit or rollback SQL commands). |
π· Example: Simple ADO.NET Flow
Imports System.Data.SqlClient
Dim con As New SqlConnection("Your_Connection_String")
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("Name"))
End While
reader.Close()
con.Close()
π· Connected vs Disconnected Model
| Feature | Connected Model | Disconnected Model |
|---|---|---|
| Main Objects | Connection, Command, DataReader | DataSet, DataTable, DataAdapter |
| Usage | Real-time, fast reading | Offline processing |
| Performance | High for small, fast operations | Efficient for large/batch tasks |
| Flexibility | Less flexible | Highly flexible |
π· Advantages of ADO.NET
- Supports both real-time and offline data processing
- Works well with various databases
- Can use strongly typed data access
- Ideal for enterprise-level applications
β Summary
| Topic | Key Points |
|---|---|
| What is ADO.NET | .NET technology for accessing and manipulating databases |
| Models Supported | Connected (DataReader), Disconnected (DataSet) |
| Main Classes | SqlConnection, SqlCommand, SqlDataReader, SqlDataAdapter |
| Use Cases | Data retrieval, updates, transactions, reporting, etc. |
"DataSet in ADO.NET"
π· What is a DataSet?
A DataSet is an in-memory cache of data retrieved from a database. It stores data in a disconnected mode, meaning once data is fetched, the connection to the database can be closed.
- It is part of the System.Data namespace.
- Can hold multiple DataTables, relationships, and constraints.
π· Key Features of DataSet
| Feature | Description |
|---|---|
| Disconnected | Works offline, no need for an open database connection. |
| Multiple Tables | Can hold multiple tables and define relationships between them. |
| XML Support | Data can be read from or written to XML. |
| Relational View | Maintains relationships like primary keys, foreign keys. |
| Data Manipulation | Supports editing, adding, deleting, and updating rows. |
π· DataSet Structure
A DataSet contains:
- DataTable(s): Individual tables with rows and columns.
- DataRelation(s): Define relationships between tables (like foreign keys).
- Constraints: Ensure data integrity (e.g., uniqueness, primary key).
DataSet
βββ DataTable: Students
βββ DataTable: Courses
βββ DataRelation: Students β Courses
π· Basic Syntax (VB.NET Example)
Imports System.Data
Imports System.Data.SqlClient
Dim con As New SqlConnection("Your_Connection_String")
Dim da As New SqlDataAdapter("SELECT * FROM Students", con)
Dim ds As New DataSet()
' Fill DataSet with data from database
da.Fill(ds, "Students")
' Access data
Dim dt As DataTable = ds.Tables("Students")
For Each row As DataRow In dt.Rows
Console.WriteLine(row("Name"))
Next
π· Working with DataSet
| Task | Code Example |
|---|---|
| Create a DataSet | Dim ds As New DataSet() |
| Add a DataTable | ds.Tables.Add(New DataTable("Employees")) |
| Access a DataTable | ds.Tables("Employees") |
| Read data from rows | row("ColumnName") |
| Write to XML | ds.WriteXml("data.xml") |
| Read from XML | ds.ReadXml("data.xml") |
π· Differences: DataSet vs DataReader
| Feature | DataSet | DataReader |
|---|---|---|
| Connection | Disconnected | Connected |
| Flexibility | High β multiple tables, XML, etc. | Low β forward-only |
| Performance | Slower (for large data) | Faster |
| Use Case | Batch processing, offline operations | Fast, read-only access |
π· Advantages of DataSet
- No need to keep the connection open after fetching data.
- Supports complex data operations (like table relations).
- Works well with XML for import/export.
- Good for Windows Forms and reporting apps.
β Summary
| Property | Description |
|---|---|
| Class | System.Data.DataSet |
| Use | Offline data storage and manipulation |
| Contains | DataTables, DataRelations, Constraints |
| Common Methods | .Tables, .WriteXml(), .ReadXml(), .Clear() |
"Connecting to a Database"
π· What is a Database Connection?
A database connection is a link between your .NET application and the database server (e.g., SQL Server). It allows your program to send queries, fetch data, and perform operations like insert, update, or delete.
π· Key Object: SqlConnection
- Provided by the
System.Data.SqlClientnamespace. - Used to open and manage the connection to a SQL Server database.
π· Basic Steps to Connect
- Import the Namespace
vb.net
Imports System.Data.SqlClient
- Declare Connection String A string that holds info to locate and connect to the database.
vb.net
Dim conStr As String = "Data Source=SERVER_NAME;Initial Catalog=DB_NAME;Integrated Security=True"
Or using SQL login:
vb.net
Dim conStr As String = "Data Source=SERVER_NAME;Initial Catalog=DB_NAME;User ID=yourUsername;Password=yourPassword"
- Create Connection Object
vb.net
Dim con As New SqlConnection(conStr)
- Open the Connection
vb.net
con.Open()
-
Perform Operations (Select, Insert, etc.)
-
Close the Connection
vb.net
con.Close()
π· Example: Connecting to SQL Server and Retrieving Data
Imports System.Data.SqlClient
Module Module1
Sub Main()
Dim conStr As String = "Data Source=.\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True"
Dim con As New SqlConnection(conStr)
Try
con.Open()
Console.WriteLine("Connection Successful!")
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine("Name: " & reader("Name"))
End While
reader.Close()
Catch ex As Exception
Console.WriteLine("Error: " & ex.Message)
Finally
con.Close()
End Try
End Sub
End Module
π· Important Properties and Methods
| Property / Method | Description |
|---|---|
.Open() |
Opens the database connection |
.Close() |
Closes the connection |
.State |
Checks the state (Open/Closed) of the connection |
.ConnectionString |
Sets or gets the connection string |
π· Best Practices
- Always close the connection after operations (use
Finallyblock). - Use
Usingblock to ensure automatic disposal of resources. - Avoid hardcoding credentials β use configuration files.
β Summary
| Concept | Details |
|---|---|
| Purpose | To link .NET application with the database |
| Main Class | SqlConnection (from System.Data.SqlClient) |
| Process | Define connection string β Open connection β Work β Close |
| Error Handling | Use TryβCatchβFinally or Using block |
βIntroduction to Database Programmingβ
π Topic: Introduction to Database Programming
π· What is Database Programming?
Database Programming refers to writing code in a programming language (like VB.NET or C#) to interact with a database system (like SQL Server, Oracle, MySQL).
It allows applications to:
- Store data permanently
- Retrieve data when needed
- Update or delete existing records
- Perform transactions and data validation
π· Why Database Programming is Important?
| Reason | Explanation |
|---|---|
| Data Storage | Store and manage large volumes of structured data |
| Data Access | Retrieve specific data efficiently |
| Automation | Automate business logic using stored procedures or queries |
| User Interaction | Create interactive applications (like student records, billing systems) |
| Security & Integrity | Ensure controlled access and maintain data accuracy |
π· Common Operations in Database Programming
| Operation | Purpose |
|---|---|
| Connect | Establish a connection to the database |
| Insert | Add new records to the database |
| Select | Retrieve data from the database |
| Update | Modify existing records |
| Delete | Remove records |
These operations are commonly called CRUD: Create, Read, Update, Delete.
π· Tools and Technologies Used
| Technology | Purpose |
|---|---|
| ADO.NET | .NET framework component for data access |
| SQL | Language for querying and managing databases |
| Visual Studio | IDE for developing database applications |
| Database Servers | SQL Server, Oracle, MySQL, etc. |
π· ADO.NET in Database Programming
ADO.NET is the primary data access technology in .NET. It offers:
- Connected model using
SqlConnection,SqlCommand,SqlDataReader - Disconnected model using
DataSet,DataTable,DataAdapter - Support for transactions, XML, schemas, and data binding
π· Example: Simple Database Operation (VB.NET)
Imports System.Data.SqlClient
Dim con As New SqlConnection("Data Source=.;Initial Catalog=SchoolDB;Integrated Security=True")
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
con.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("Name"))
End While
reader.Close()
con.Close()
π· Advantages of Database Programming
| Advantage | Explanation |
|---|---|
| Centralized Storage | Keeps data in one place |
| Data Integrity | Ensures accuracy and consistency |
| Scalability | Handles growing amounts of data |
| Security | User-level permissions and authentication |
| Performance | Optimized querying through indexes and keys |
β Summary
| Topic | Key Points |
|---|---|
| What is it? | Programming to interact with databases |
| Tools Used | ADO.NET, SQL, Visual Studio, SQL Server, etc. |
| Operations Performed | CRUD: Create, Read, Update, Delete |
| Benefits | Secure, fast, reliable, and structured data management |
βMicrosoft Access 2003β
π· What is Microsoft Access 2003?
Microsoft Access 2003 is a relational database management system (RDBMS) developed by Microsoft. It allows users to create, manage, and interact with databases using a graphical interface and SQL.
It is often used for small to medium-sized database applications and integrates well with other Microsoft Office products.
π· Features of Microsoft Access 2003
| Feature | Description |
|---|---|
| User-Friendly Interface | Easy-to-use GUI for managing tables, queries, forms, and reports. |
| Tables | Used to store data in rows and columns. |
| Queries | Used to filter, sort, and retrieve specific data using SQL or query builder. |
| Forms | Interface for entering or viewing data in a user-friendly way. |
| Reports | Used for formatting and printing data summaries or outputs. |
| Macros | Automates repetitive tasks without coding. |
| VBA Integration | Supports Visual Basic for Applications for advanced programming. |
π· Objects in Microsoft Access
| Object | Description |
|---|---|
| Table | Stores raw data. Each table consists of rows (records) and columns (fields). |
| Query | Used to search and filter data. Can use SQL or query design view. |
| Form | Data-entry screen for viewing or entering records. |
| Report | Formats and presents data for printing or sharing. |
| Macro | Automates tasks (like opening forms, running queries). |
| Module | Contains VBA code for advanced operations. |
π· Creating a Simple Database in Access 2003
- Open Access 2003
- Create a new database β File > New > Blank Database
- Create Tables β Design View (define field names and data types)
- Set Primary Key β Unique identifier (e.g., StudentID)
- Enter Data β Datasheet View
- Create Queries β Use Query Wizard or SQL
- Design Forms β For data input
- Generate Reports β For printable output
π· Common Data Types in Access
| Data Type | Description |
|---|---|
| Text | Alphanumeric values (up to 255 chars) |
| Memo | Long text (more than 255 chars) |
| Number | Numeric data (integer, decimal, etc.) |
| Date/Time | Dates and times |
| Currency | Financial values with formatting |
| Yes/No | Boolean (True/False) |
| AutoNumber | Auto-incrementing primary key |
π· Microsoft Access 2003 with VB.NET / ADO.NET
You can connect an Access 2003 .mdb file with VB.NET using OLEDB.
β Example Connection String:
Dim conStr As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\yourfile.mdb;"
Dim con As New OleDbConnection(conStr)
con.Open()
β Required Namespace:
Imports System.Data.OleDb
π· Advantages of Access 2003
| Advantage | Explanation |
|---|---|
| Easy to Learn | Ideal for beginners and non-programmers |
| Office Integration | Works well with Excel, Word, Outlook |
| Rapid Development | Quick creation of forms, queries, reports |
| Small Business Friendly | Suitable for small/medium scale applications |
| Desktop-based | No need for complex server setup |
π· Limitations
- Not ideal for high-traffic multi-user environments.
- Limited scalability compared to SQL Server or Oracle.
- File-based (prone to corruption in large usage scenarios).
β Summary
| Topic | Details |
|---|---|
| What is it? | GUI-based relational database system |
| Main Objects | Table, Query, Form, Report, Macro, Module |
| File Format | .mdb (Access 2003 format) |
| Used In | Small business apps, prototyping, data entry systems |
| Integration | Can be connected to .NET using OleDb |
"Database Programming"
π· What is Database Programming?
Database Programming involves writing code to interact with a Database Management System (DBMS). It allows software applications to:
- Store,
- Retrieve,
- Update, and
- Delete data from databases.
In .NET, this is commonly done using ADO.NET and languages like VB.NET or C#.
π· Why is Database Programming Important?
| Feature | Purpose |
|---|---|
| Data Storage | Store structured information permanently |
| Data Retrieval | Fetch required data efficiently using queries |
| Data Management | Easily modify and organize records |
| Integration | Connect with GUI forms, reports, and business logic |
| Security and Integrity | Enforce rules, permissions, and validations |
π· Basic Concepts in Database Programming
-
Database A collection of organized data (e.g., Student Records, Inventory, etc.).
-
Table Contains data in rows and columns. Each row is a record; each column is a field.
-
SQL (Structured Query Language) A standard language to query and manipulate databases.
-
CRUD Operations Common operations in database programming:
-
Create β Insert new records
- Read β Retrieve records
- Update β Modify existing records
- Delete β Remove records
π· Tools Used in Database Programming
| Tool/Technology | Purpose |
|---|---|
| ADO.NET | .NET library to access databases (SQL, Access, etc.) |
| SQL | Language used to query the database |
| VB.NET / C# | Programming languages to write database logic |
| Visual Studio | IDE to design forms and write code |
| MS SQL Server / Access | Common DBMS used in .NET applications |
π· ADO.NET in Database Programming
ADO.NET is a key technology in .NET for working with databases. It provides:
-
Connected Model: Works with live data using
SqlConnection,SqlCommand,SqlDataReader. -
Disconnected Model: Uses
DataSet,DataTable, andDataAdapterto work offline.
π· Database Programming Workflow in .NET
-
Create and Design Database Use tools like MS Access or SQL Server.
-
Write Connection Code Use
SqlConnectionorOleDbConnection. -
Execute SQL Commands Use
SqlCommandto run queries. -
Read Data Use
SqlDataReaderorDataSetto read the results. -
Bind Data to Controls Display data in controls like
DataGridView,TextBox, etc. -
Close Connection Always close the connection to free resources.
π· Example Code (VB.NET with SQL Server)
Imports System.Data.SqlClient
Dim conStr As String = "Data Source=.\SQLEXPRESS;Initial Catalog=StudentDB;Integrated Security=True"
Dim con As New SqlConnection(conStr)
con.Open()
Dim cmd As New SqlCommand("SELECT * FROM Students", con)
Dim reader As SqlDataReader = cmd.ExecuteReader()
While reader.Read()
Console.WriteLine(reader("Name"))
End While
reader.Close()
con.Close()
π· Advantages of Database Programming
| Advantage | Description |
|---|---|
| Efficient Data Access | Speeds up storing and retrieving data |
| Reusability | SQL queries and procedures can be reused |
| Scalability | Easily manage large volumes of data |
| Integration | Works well with GUIs, reports, and web applications |
| Security | Role-based access and data validation mechanisms |
β Summary
| Concept | Description |
|---|---|
| Definition | Writing code to interact with a database |
| Core Technologies | SQL, ADO.NET, VB.NET, Visual Studio |
| Main Operations | CRUD (Create, Read, Update, Delete) |
| Tools | SQL Server, MS Access, Visual Studio |
"Bound Controls"
π· What are Bound Controls?
Bound controls are form controls (like TextBox, ComboBox, DataGridView) that are linked to a data source such as a DataSet, DataTable, or a database.
When a bound control is connected, it automatically displays and updates the data from the source without needing manual code for every field.
π· Purpose of Bound Controls
- To connect UI elements directly to database fields
- To display data automatically in forms
- To simplify data entry, editing, and viewing
- To reduce the amount of code needed for data manipulation
π· Examples of Bound Controls
| Control Type | Description |
|---|---|
| TextBox | Displays text from a database field |
| ComboBox | Displays a list of values from a table/column |
| DataGridView | Displays entire table records in tabular format |
| Label | Shows read-only data from a data source |
π· Types of Data Binding
| Type | Description |
|---|---|
| Simple Binding | Binds a single control to a single field (e.g., TextBox to βNameβ) |
| Complex Binding | Binds a control to multiple fields or a list (e.g., DataGridView to table) |
π· Example: Binding a TextBox to a Dataset Field
TextBox1.DataBindings.Add("Text", DataSet1.Tables("Students"), "Name")
- This binds
TextBox1to theNamecolumn in theStudentstable.
π· Example: Binding a DataGridView to a Table
DataGridView1.DataSource = DataSet1.Tables("Students")
- This displays all student records in a grid view.
π· Steps to Create Bound Controls in Visual Studio
- Create a Data Source (e.g., SQL Server, Access)
- Add a DataSet to your project
- Design a Form and drag controls (TextBox, DataGridView, etc.)
- Set the DataSource and DataBindings in code or using designer
- Run the application to view/edit database records
π· Advantages of Bound Controls
| Advantage | Description |
|---|---|
| Automatic Sync | Reflects changes instantly between UI and data source |
| Reduces Code | Eliminates the need for manual data transfer |
| Easier UI Design | Visual Studio provides drag-and-drop binding tools |
| Faster Development | Speeds up building data-driven applications |
π· Disadvantages
| Limitation | Explanation |
|---|---|
| Less Flexibility | Difficult to customize data processing |
| Performance Issues | May slow down for large datasets |
| Complex Debugging | Errors may not be as clear as in manual data handling |
β Summary
| Point | Details |
|---|---|
| What is it? | Control linked to a data source to display/edit values |
| Examples | TextBox, ComboBox, DataGridView |
| Binding Types | Simple (single field) and Complex (tables/lists) |
| Usage | Ideal for data entry forms, dashboards, admin panels |
βBasic SQL Statementsβ
π· What is SQL?
SQL (Structured Query Language) is the standard language used to communicate with relational databases. It is used for storing, retrieving, modifying, and deleting data.
π· Categories of SQL Statements
| Category | Purpose |
|---|---|
| DML (Data Manipulation Language) | Used to manipulate data (INSERT, SELECT, UPDATE, DELETE) |
| DDL (Data Definition Language) | Used to define or change structure (CREATE, ALTER, DROP) |
| DCL (Data Control Language) | Controls access to data (GRANT, REVOKE) |
| TCL (Transaction Control Language) | Manages transactions (COMMIT, ROLLBACK, SAVEPOINT) |
πΉ 1. DML β Data Manipulation Language
β
SELECT β Retrieve data
SELECT * FROM Students;
SELECT Name, Age FROM Students WHERE Age > 18;
β
INSERT β Add new record
INSERT INTO Students (Name, Age) VALUES ('John', 20);
β
UPDATE β Modify existing data
UPDATE Students SET Age = 21 WHERE Name = 'John';
β
DELETE β Remove data
DELETE FROM Students WHERE Name = 'John';
πΉ 2. DDL β Data Definition Language
β
CREATE TABLE β Define a new table
CREATE TABLE Students (
StudentID INT PRIMARY KEY,
Name VARCHAR(50),
Age INT
);
β
ALTER TABLE β Modify table structure
ALTER TABLE Students ADD Email VARCHAR(100);
β
DROP TABLE β Delete entire table
DROP TABLE Students;
πΉ 3. DCL β Data Control Language
β
GRANT β Give permission
GRANT SELECT, INSERT ON Students TO user1;
β
REVOKE β Take back permission
REVOKE INSERT ON Students FROM user1;
πΉ 4. TCL β Transaction Control Language
β
COMMIT β Save transaction permanently
COMMIT;
β
ROLLBACK β Undo changes since last commit
ROLLBACK;
β
SAVEPOINT β Set a point to roll back to
SAVEPOINT point1;
ROLLBACK TO point1;
π· Common SQL Clauses
| Clause | Purpose |
|---|---|
| WHERE | Filter records based on condition |
| ORDER BY | Sort records (ASC or DESC) |
| GROUP BY | Group rows with same values in columns |
| HAVING | Filter grouped data (like WHERE for GROUP BY) |
| JOIN | Combine data from two or more tables |
| LIKE | Search using pattern matching (LIKE 'A%') |
| IN | Match against multiple values (IN (10, 20, 30)) |
π· Example Queries
π Select all students whose age is greater than 18:
SELECT * FROM Students WHERE Age > 18;
π Insert a new student record:
INSERT INTO Students (Name, Age) VALUES ('Alice', 22);
π Update a studentβs name:
UPDATE Students SET Name = 'Alice Smith' WHERE Name = 'Alice';
π Delete students younger than 18:
DELETE FROM Students WHERE Age < 18;
β Summary
| Topic | Description |
|---|---|
| SQL | Language to work with relational databases |
| Basic Commands | SELECT, INSERT, UPDATE, DELETE |
| DDL Commands | CREATE, ALTER, DROP |
| DCL & TCL | GRANT, REVOKE, COMMIT, ROLLBACK |
| Useful Clauses | WHERE, ORDER BY, GROUP BY, HAVING, JOIN |
LINQ
π· What is LINQ?
- LINQ stands for Language Integrated Query.
- It is a .NET Framework feature that adds native query capabilities directly into C# and VB.NET.
- Allows querying collections, databases, XML, and more in a consistent way.
- Integrates query syntax inside the programming language itself.
π· Why use LINQ?
| Benefit | Description |
|---|---|
| Simplifies Queries | Write complex queries in a readable syntax |
| Strongly Typed | Checked at compile time, reducing runtime errors |
| Consistent | Same syntax to query different data sources |
| Integration | Works with arrays, lists, XML, databases, etc. |
π· LINQ Query Structure
var result = from item in collection
where condition
orderby item.Property
select item;
- from: Source collection
- where: Filter condition
- orderby: Sort results
- select: Specify output
π· Types of LINQ
| Type | Description |
|---|---|
| LINQ to Objects | Query in-memory collections like arrays, lists |
| LINQ to SQL | Query SQL Server databases directly |
| LINQ to XML | Query and manipulate XML documents |
| LINQ to Entities | Works with Entity Framework and databases |
π· Example: LINQ to Objects (C#)
int[] numbers = { 2, 4, 6, 8, 10 };
var evenNumbers = from num in numbers
where num % 2 == 0
select num;
foreach(var n in evenNumbers)
{
Console.WriteLine(n);
}
π· Benefits in .NET Programming
- Reduces boilerplate code for filtering and sorting.
- Makes code more declarative and easier to read.
- Enables deferred execution β queries run when results are enumerated.
- Supports lambda expressions and method syntax for queries.
π· Lambda Expression Syntax (Alternate to Query Syntax)
var evenNumbers = numbers.Where(n => n % 2 == 0);
β Summary
| Point | Description |
|---|---|
| LINQ | Integrated query syntax in .NET languages |
| Purpose | Query collections, databases, XML easily |
| Syntax | Query syntax (from-where-select) or method syntax (lambda) |
| Supports | LINQ to Objects, LINQ to SQL, LINQ to XML, LINQ to Entities |
Filtering Data
π· What is Filtering Data?
- Filtering data means selecting a subset of records from a data source based on specific conditions.
- It helps to retrieve only relevant data instead of the entire dataset.
- Filtering is essential in databases, collections, and LINQ queries to work efficiently with large data.
π· Filtering in SQL
- The WHERE clause is used to filter rows in SQL queries.
- It specifies conditions that each row must satisfy to be included in the result.
Example:
SELECT * FROM Employees WHERE Department = 'Sales';
- This query returns only employees in the Sales department.
π· Filtering in ADO.NET
- When using ADO.NET, you can filter data in a DataTable using the
Selectmethod or DataView.
Using DataTable.Select:
DataRow[] filteredRows = dataTable.Select("Age > 30 AND City = 'Mumbai'");
Using DataView:
DataView dv = new DataView(dataTable);
dv.RowFilter = "Age > 30 AND City = 'Mumbai'";
- Both ways allow filtering rows based on expressions similar to SQL WHERE.
π· Filtering Data Using LINQ
- LINQ provides a natural and type-safe way to filter collections with the
wherekeyword.
Example (LINQ to Objects):
var filteredList = from emp in employees
where emp.Age > 30 && emp.City == "Mumbai"
select emp;
- Using Lambda expressions:
var filteredList = employees.Where(emp => emp.Age > 30 && emp.City == "Mumbai");
π· Common Filtering Operators
| Operator | Description | Example |
|---|---|---|
= |
Equal to | City = 'Mumbai' |
<> or != |
Not equal to | Age <> 25 |
> |
Greater than | Salary > 50000 |
< |
Less than | Age < 60 |
>= |
Greater than or equal to | Experience >= 5 |
<= |
Less than or equal to | Age <= 30 |
LIKE |
Pattern matching (SQL) | Name LIKE 'A%' |
IN |
Matches any value in a list | City IN ('Mumbai', 'Delhi') |
AND |
Logical AND | Combine multiple conditions |
OR |
Logical OR | Combine multiple conditions |
NOT |
Negates a condition | NOT City = 'Mumbai' |
π· Filtering with Multiple Conditions
- Combine multiple conditions with
ANDandORto form complex filters.
SQL Example:
SELECT * FROM Employees WHERE Department = 'Sales' AND Age > 30;
LINQ Example:
var filtered = employees.Where(e => e.Department == "Sales" && e.Age > 30);
π· Filtering Null or Empty Values
- Check for
NULLvalues in SQL:
SELECT * FROM Employees WHERE ManagerID IS NULL;
- Check for null or empty strings in C#:
var filtered = employees.Where(e => !string.IsNullOrEmpty(e.Name));
π· Benefits of Filtering Data
| Benefit | Description |
|---|---|
| Improves performance | Retrieves only required data, reducing load |
| Simplifies data handling | Easier to work with smaller, relevant datasets |
| Enhances user experience | Shows focused results matching user criteria |
β Summary
| Aspect | Description |
|---|---|
| Filtering Purpose | Select subset of data matching conditions |
| SQL Filtering | Use WHERE clause |
| ADO.NET Filtering | Use DataTable.Select or DataView.RowFilter |
| LINQ Filtering | Use where clause or .Where() method |
| Logical Operators | AND, OR, NOT for complex conditions |
| Pattern Matching | Use LIKE and IN for flexible filtering |