SlideShare a Scribd company logo
1 of 27
Download to read offline
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 1
Hello everyone , my name is Salman Mushtaq and I am student of IT in Punjab University , Pakistan.
I try my best to clear the concept .
In this Chapter we cover following:
- Database Connectivity
- Selection of data
- Insertion of data
- Insertion of data (parameterized query)
- Updation
- Deletion
- DataTable(In-Memory Databse)
- Dataset
- DataRelation
- DataAdapter
Ok let start from Database Connectivity.
DATABASE
Hum database “File” or “Console” k alternate main use kartay han .
Database say jab bhi data fetch karna hota hai hamain aik cost deni parti hai jo “File” k case main nai
deni parti but file is not efficient or protected way .
Jab bhi hum database say ko apne program main include karain gay hamain database create karni
pare gi . Main yahain Visual Stdio 2012 use kar raha hun aye daikhtay hain k yey sara kam kaise
huga.
STEPS
1- Open Visual Studio 2012
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 2
2- Create new project
3- Select Visual C# and Console Application and named it
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 3
After , this screen will appear
4- Now right click on name space that is on right side that is name of your application
Add => New Item => Data => Service based Database and named it with extension .mdf
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 4
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 5
5- Now this appear on main screen
6- Now create table in it and insert some data
Double click on database name in server explorer => right click on table => add new table =>
Fill table property and named it finally and some data by click on table name => show table data
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 6
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 7
Ok now create SqlConnection object and pass Path of database
You get path of your database by double click on your database its properties was shown here
you copy the ConnectionString .
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 8
In this chapter all students note that following:
Database Name : Student
Table Name : Stu(Id , Name , Mobile)
Now see the code and try to create understanding .
Remember out database name is Student.mdf and table name is Stu(Id,Name,Mobile).
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
string cs = @"Data
Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In
tegrated Security=True";
SqlConnection con = new SqlConnection(cs);
string query = "select * from Stu";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 9
Console.Write("Id : " + dr["Id"]);
Console.Write("Name : " + dr["Name"]);
Console.WriteLine("Mobile No : " + dr["Mobile"]);
}
con.Close();
}
}
}
Output:
Ok selection is complete now
INSERTION
See code and understand
Database before insertion
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 10
Database after insertion:
Ok let we start the coding and then we show you the Output.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
string cs = @"Data
Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In
tegrated Security=True";
SqlConnection con = new SqlConnection(cs);
String n, m;
int i = 4; // We initialize Id as i=4 because we have three records already
// Afterwards you make your primary key AutoIncrement
Console.WriteLine("Enter Name");
n = Console.ReadLine();
Console.WriteLine("Enter Mobile Number");
m = Console.ReadLine();
string query = "Insert into Stu(Id,Name,Mobile) Values ('" + i + "','" + n +
"','" + m + "')";
SqlCommand cmd = new SqlCommand(query, con);
con.Open();
int dr = cmd.ExecuteNonQuery();
if (dr > 0)
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 11
Console.WriteLine(dr + " row inserted successfully");
con.Close();
}
}
}
See the output:
Our database
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 12
Now there is 4 records …
Ok I hope you enjoy the database programming
Now we insert Record 5 with parameterized query:
Let see the code and understand:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
string cs = @"Data
Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In
tegrated Security=True";
SqlConnection con = new SqlConnection(cs);
String n, m;
int i = 5; // We initialize Id as i=5 because we have three records already
// Afterwards you make your primary key AutoIncrement
Console.WriteLine("Enter Name");
n = Console.ReadLine();
Console.WriteLine("Enter Mobile Number");
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 13
m = Console.ReadLine();
string query = "Insert into Stu(Id,Name,Mobile) values(@I , @N, @M)";
// Because we insert data through parameterized so we create SqlParameter
object
// and add it into Command
SqlParameter p1 = new SqlParameter("I",i);
SqlParameter p2 = new SqlParameter("N",n);
SqlParameter p3 = new SqlParameter("M",m);
SqlCommand cmd = new SqlCommand(query, con);
// Add parameters
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
con.Open();
int dr = cmd.ExecuteNonQuery();
if (dr > 0)
Console.WriteLine(dr + " row inserted successfully");
con.Close();
}
}
}
Output:
Ok now see database
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 14
You see there are 5 records in a database:
Ok now Insertion is complete . Let we start Updation of data in C# (DataBase).
Update:
See code and understand:
Before updation:
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 15
Code: // We want to update the record 1
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
string cs = @"Data
Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In
tegrated Security=True";
SqlConnection con = new SqlConnection(cs);
String m;
int i ;
Console.WriteLine("Enter Valid Id");
i = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Mobile Number");
m = Console.ReadLine();
string query = "Update Stu set Mobile=@M where Id=@i";
SqlParameter p1 = new SqlParameter("I",i);
SqlParameter p2 = new SqlParameter("M",m);
SqlCommand cmd = new SqlCommand(query, con);
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 16
// Add parameters
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
con.Open();
int dr = cmd.ExecuteNonQuery();
if (dr > 0)
Console.WriteLine(dr + " row updated successfully");
else
Console.WriteLine("Invalid Id");
con.Close();
}
}
}
After Updation:
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 17
Ok updation is complete now we go to Deletion:
Delete:
We want to delete Record 5
Code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
string cs = @"Data
Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In
tegrated Security=True";
SqlConnection con = new SqlConnection(cs);
String m;
int i ;
Console.WriteLine("Enter Valid Id");
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 18
i = int.Parse(Console.ReadLine());
string query = "Delete from Stu where Id=@i";
SqlParameter p1 = new SqlParameter("I",i);
SqlCommand cmd = new SqlCommand(query, con);
// Add parameters
cmd.Parameters.Add(p1);
con.Open();
int dr = cmd.ExecuteNonQuery();
if (dr > 0)
Console.WriteLine(dr + " row deleted successfully");
else
Console.WriteLine("Invalid Id");
con.Close();
}
}
}
Output:
Database:
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 19
Ok Students omeed hai app ab tak koi problem nai hui hu gi understanding main .
But if you have any problem contact me any time without any hesitation.
Salman Mushtaq
Mitf12a006@pucit.edu.pk
03337465571
FaceBook:
https://www.facebook.com/salman.mushtaq.39
Ok now we start next topic that is DataTable:
DataTable:
“When we want in-memory database than we use DataTabe , datatable contains some
properties like DataColumn , DataRow etc ” .
Ok let implement this concept.
Hum jab bhi database k sath connectivity kartay hain hamain kuch cost deni parti hai us cost se
bachnay k liye hum DataTable (In-Memory) concept use kartay han.
Code :
Steps;
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 20
1: Create DataTable object (Create Table), than columns , than rows than insert data , select data
, update data , delete data ……
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
DataTable Table1 = new DataTable("Table1");
// We have three columns as in Stu(Id,Name,Mobile)
DataColumn Id = new DataColumn("Id", typeof(int));
DataColumn Name = new DataColumn("Name", typeof(string));
DataColumn Mobile = new DataColumn("Mobile", typeof(string));
// Add these Columns in datatable
Table1.Columns.Add(Id);
Table1.Columns.Add(Name);
Table1.Columns.Add(Mobile);
// Every table must have primary key so now we make Id as primary key
Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be
Primary key
// will be composite
// If we want to make primary key as auto Increamet than use this below code
that is in comments
// Id.AutoIncrement = true;
// Id.AutoIncrementSeed = 1; // kahain say start hu
// Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu
// we cannot make primary key as auto increament
// Add Data
DataRow r1 = Table1.NewRow(); // Make a new row in table
string n, m;
int i = 1;
Console.WriteLine("Enter Id");
i = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Name");
n = Console.ReadLine();
Console.WriteLine("Enter Mobile");
m = Console.ReadLine();
// Now add row into table
r1["Id"] = i;
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 21
r1["Name"] = n;
r1["Mobile"] = m;
Table1.Rows.Add(r1);
//Select data
// We can select data though row index that is start from 0
// DataRow r = Table1.Rows[0];
// We can select data through primary key
// DataRow r = Table1.Rows.Find(PrimaryKey);
// We can select data through some criteria
// DataRow[] r = Table1.Select("Name like '%Fallen'");
// We can select data through some selection creteria
DataRow[] row = Table1.Select("Name like 'Salman%'");
foreach (DataRow r in row)
{
Console.WriteLine("Id is : " + r["Id"]);
Console.WriteLine("Name is : " + r["Name"]);
Console.WriteLine("Mobile is : " + r["Mobile"]);
}
}
}
}
Output:
Ok this is Insertion and Selection now Updation
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 22
Update DataTable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
DataTable Table1 = new DataTable("Table1");
// We have three columns as in Stu(Id,Name,Mobile)
DataColumn Id = new DataColumn("Id", typeof(int));
DataColumn Name = new DataColumn("Name", typeof(string));
DataColumn Mobile = new DataColumn("Mobile", typeof(string));
// Add these Columns in datatable
Table1.Columns.Add(Id);
Table1.Columns.Add(Name);
Table1.Columns.Add(Mobile);
// Every table must have primary key so now we make Id as primary key
Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be
Primary key
// will be composite
// If we want to make primary key as auto Increamet than use this below code
that is in comments
// Id.AutoIncrement = true;
// Id.AutoIncrementSeed = 1; // kahain say start hu
// Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu
// we cannot make primary key as auto increament
// Add Data
DataRow r1 = Table1.NewRow(); // Make a new row in table
string n, m;
int i = 1;
Console.WriteLine("Enter Id");
i = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Name");
n = Console.ReadLine();
Console.WriteLine("Enter Mobile");
m = Console.ReadLine();
// Now add row into table
r1["Id"] = i;
r1["Name"] = n;
r1["Mobile"] = m;
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 23
Table1.Rows.Add(r1);
foreach (DataRow r in Table1.Rows)
{
Console.WriteLine("Id is : " + r["Id"]);
Console.WriteLine("Name is : " + r["Name"]);
Console.WriteLine("Mobile is : " + r["Mobile"]);
}
int pk;
string mob;
Console.WriteLine("Enter Id");
pk = int.Parse(Console.ReadLine());
DataRow urow = Table1.Rows.Find(pk);
Console.WriteLine("Enter New Mobile number");
mob = Console.ReadLine();
urow["Mobile"] = mob;
Console.WriteLine("-------------");
Console.WriteLine("Update data");
foreach (DataRow r in Table1.Rows)
{
Console.WriteLine("Id is : " + r["Id"]);
Console.WriteLine("Name is : " + r["Name"]);
Console.WriteLine("Mobile is : " + r["Mobile"]);
}
}
}
}
Output:
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 24
Ok now we want to delete some data :
Delete DataTable:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data.SqlClient;
using System.Data;
namespace SalmanMushtaq
{
class Program
{
static void Main(string[] args)
{
DataTable Table1 = new DataTable("Table1");
// We have three columns as in Stu(Id,Name,Mobile)
DataColumn Id = new DataColumn("Id", typeof(int));
DataColumn Name = new DataColumn("Name", typeof(string));
DataColumn Mobile = new DataColumn("Mobile", typeof(string));
// Add these Columns in datatable
Table1.Columns.Add(Id);
Table1.Columns.Add(Name);
Table1.Columns.Add(Mobile);
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 25
// Every table must have primary key so now we make Id as primary key
Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be
Primary key
// will be composite
// If we want to make primary key as auto Increamet than use this below code
that is in comments
// Id.AutoIncrement = true;
// Id.AutoIncrementSeed = 1; // kahain say start hu
// Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu
// we cannot make primary key as auto increament
// Add Data
DataRow r1 = Table1.NewRow(); // Make a new row in table
string n, m;
int i = 1;
Console.WriteLine("Enter Id");
i = int.Parse(Console.ReadLine());
Console.WriteLine("Enter Name");
n = Console.ReadLine();
Console.WriteLine("Enter Mobile");
m = Console.ReadLine();
// Now add row into table
r1["Id"] = i;
r1["Name"] = n;
r1["Mobile"] = m;
Table1.Rows.Add(r1);
foreach (DataRow r in Table1.Rows)
{
Console.WriteLine("Id is : " + r["Id"]);
Console.WriteLine("Name is : " + r["Name"]);
Console.WriteLine("Mobile is : " + r["Mobile"]);
}
int pk;
Console.WriteLine("Enter Id");
pk = int.Parse(Console.ReadLine());
// Delete through index
//Table1.Rows.RemoveAt(0);
// Delete through primary key
DataRow drow = Table1.Rows.Find(pk);
Table1.Rows.Remove(drow);
Console.WriteLine("------------------");
foreach (DataRow r in Table1.Rows)
{
Console.WriteLine("Id is : " + r["Id"]);
Console.WriteLine("Name is : " + r["Name"]);
Console.WriteLine("Mobile is : " + r["Mobile"]);
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 26
}
}
}
}
Output :
You note that after --------------- line there is no data but there is code for print data this is because the
data will be deleted.
Ok Datable is complete
Now we move to our next topic that is DataRelation or Dataset but before doing this we do
DataAdapter.
DataAdapter:
Ok hamain pata hai k DataTable temporary hota hai jaise hi execution end hoti hai memory end hu jati
hai jo us ko RAM main allocate hui hoti hai lehaza DataTable tu in-memory table hai lehaza wo bhi
khatam hu jata hai , tu kiya ab hum har bar data insert karain gay aur phir koi calculation karain gay nai ,
hum aysa karain gay k in memory datatabe main data database say fill kar lain gay is ka faida yey hug a k
hamain database k sath connectivity sirf aik bar karni paray gi , aur baqi kam in memory tables say hu jae
ga ,
Is kam k liye hum DataAdapter use kartay hain .
Database in C# By Salman Mushtaq
Mitf12a006@pucit.edu.pk Page 27
DataAdapter k kuch methods hain
1. Fill
2. Update
Jab bhi data fill karna hug a hum fill ka method call karain gay with select query
Aur baqi tamam queries(update,delete,insert) k liye update ka function call karain gay.

More Related Content

What's hot

Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iiiNiraj Bharambe
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeNicolas Bettenburg
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer iiIsabella789
 
Simpan data- ke- database
Simpan data- ke- databaseSimpan data- ke- database
Simpan data- ke- databaseTri Sugihartono
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepSylvain Hallé
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsMichele Capra
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputuanna
 
Java Puzzle
Java PuzzleJava Puzzle
Java PuzzleSFilipp
 
บทที่1
บทที่1บทที่1
บทที่1Palm Unnop
 

What's hot (18)

Ajax chap 4
Ajax chap 4Ajax chap 4
Ajax chap 4
 
Java jdbc
Java jdbcJava jdbc
Java jdbc
 
Ajax chap 5
Ajax chap 5Ajax chap 5
Ajax chap 5
 
xml rpc
xml rpcxml rpc
xml rpc
 
Core java pract_sem iii
Core java pract_sem iiiCore java pract_sem iii
Core java pract_sem iii
 
Ajax
AjaxAjax
Ajax
 
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source CodeUsing Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
Using Fuzzy Code Search to Link Code Fragments in Discussions to Source Code
 
Lecture6
Lecture6Lecture6
Lecture6
 
1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii1z0 804 exam-java se 7 programmer ii
1z0 804 exam-java se 7 programmer ii
 
Simpan data- ke- database
Simpan data- ke- databaseSimpan data- ke- database
Simpan data- ke- database
 
Java codes
Java codesJava codes
Java codes
 
Writing Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeepWriting Domain-Specific Languages for BeepBeep
Writing Domain-Specific Languages for BeepBeep
 
Building High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 AppsBuilding High Performance and Reliable Windows Phone 8 Apps
Building High Performance and Reliable Windows Phone 8 Apps
 
JDBC Core Concept
JDBC Core ConceptJDBC Core Concept
JDBC Core Concept
 
Parameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple inputParameterization is nothing but giving multiple input
Parameterization is nothing but giving multiple input
 
Java Puzzle
Java PuzzleJava Puzzle
Java Puzzle
 
บทที่1
บทที่1บทที่1
บทที่1
 
Python dictionaries
Python dictionariesPython dictionaries
Python dictionaries
 

Similar to Database By Salman Mushtaq

CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docxclarebernice
 
Previous weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docxPrevious weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docxkeilenettie
 
Cis407 a ilab 4 web application development devry university
Cis407 a ilab 4 web application development devry universityCis407 a ilab 4 web application development devry university
Cis407 a ilab 4 web application development devry universitylhkslkdh89009
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studioAravindharamanan S
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletMitchinson
 
Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Adooswchavez
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdfManalAg
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingMax Kleiner
 
Cis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universityCis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universitylhkslkdh89009
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.netHemant Sankhla
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalDr. Ranbijay Kumar
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySqlkamal kotecha
 
ASP.net Manual final.pdf
ASP.net Manual final.pdfASP.net Manual final.pdf
ASP.net Manual final.pdfSwapnilGujar13
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShakir Majeed Khan
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Databasejitendral
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiMuhammed Thanveer M
 
UNIT V PYTHON.pptx python basics ppt python
UNIT V PYTHON.pptx python basics ppt pythonUNIT V PYTHON.pptx python basics ppt python
UNIT V PYTHON.pptx python basics ppt pythonSuganthiDPSGRKCW
 

Similar to Database By Salman Mushtaq (20)

CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx        Greetings and Salutations.docxCIS407AWk2iLabDefault.aspx        Greetings and Salutations.docx
CIS407AWk2iLabDefault.aspx Greetings and Salutations.docx
 
Previous weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docxPrevious weeks work has been uploaded as well as any other pieces ne.docx
Previous weeks work has been uploaded as well as any other pieces ne.docx
 
Cis407 a ilab 4 web application development devry university
Cis407 a ilab 4 web application development devry universityCis407 a ilab 4 web application development devry university
Cis407 a ilab 4 web application development devry university
 
Simple ado program by visual studio
Simple ado program by visual studioSimple ado program by visual studio
Simple ado program by visual studio
 
Open microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutletOpen microsoft visual studio/tutorialoutlet
Open microsoft visual studio/tutorialoutlet
 
Microsoft Ado
Microsoft AdoMicrosoft Ado
Microsoft Ado
 
3-ADO.NET.pdf
3-ADO.NET.pdf3-ADO.NET.pdf
3-ADO.NET.pdf
 
maxbox starter72 multilanguage coding
maxbox starter72 multilanguage codingmaxbox starter72 multilanguage coding
maxbox starter72 multilanguage coding
 
Ado Presentation
Ado PresentationAdo Presentation
Ado Presentation
 
Cis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry universityCis407 a ilab 5 web application development devry university
Cis407 a ilab 5 web application development devry university
 
Mvc acchitecture
Mvc acchitectureMvc acchitecture
Mvc acchitecture
 
Database connectivity to sql server asp.net
Database connectivity to sql server asp.netDatabase connectivity to sql server asp.net
Database connectivity to sql server asp.net
 
2310 b 10
2310 b 102310 b 10
2310 b 10
 
JAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and RetrievalJAM819 - Native API Deep Dive: Data Storage and Retrieval
JAM819 - Native API Deep Dive: Data Storage and Retrieval
 
Jdbc example program with access and MySql
Jdbc example program with access and MySqlJdbc example program with access and MySql
Jdbc example program with access and MySql
 
ASP.net Manual final.pdf
ASP.net Manual final.pdfASP.net Manual final.pdf
ASP.net Manual final.pdf
 
Share pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbsShare pointtechies linqtosp-andsbs
Share pointtechies linqtosp-andsbs
 
JDBC for CSQL Database
JDBC for CSQL DatabaseJDBC for CSQL Database
JDBC for CSQL Database
 
Oop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer MelayiOop concept in c++ by MUhammed Thanveer Melayi
Oop concept in c++ by MUhammed Thanveer Melayi
 
UNIT V PYTHON.pptx python basics ppt python
UNIT V PYTHON.pptx python basics ppt pythonUNIT V PYTHON.pptx python basics ppt python
UNIT V PYTHON.pptx python basics ppt python
 

More from Salman Mushtaq

More from Salman Mushtaq (7)

Bootstrap 3 Lecture 5
Bootstrap 3 Lecture 5Bootstrap 3 Lecture 5
Bootstrap 3 Lecture 5
 
LINQ to SQL
LINQ to SQLLINQ to SQL
LINQ to SQL
 
Captcha
CaptchaCaptcha
Captcha
 
ADO DOT NET
ADO DOT NETADO DOT NET
ADO DOT NET
 
Contact Book Version 1.0
Contact Book Version 1.0Contact Book Version 1.0
Contact Book Version 1.0
 
Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-Entity frame work by Salman Mushtaq -1-
Entity frame work by Salman Mushtaq -1-
 
Serialization
SerializationSerialization
Serialization
 

Database By Salman Mushtaq

  • 1. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 1 Hello everyone , my name is Salman Mushtaq and I am student of IT in Punjab University , Pakistan. I try my best to clear the concept . In this Chapter we cover following: - Database Connectivity - Selection of data - Insertion of data - Insertion of data (parameterized query) - Updation - Deletion - DataTable(In-Memory Databse) - Dataset - DataRelation - DataAdapter Ok let start from Database Connectivity. DATABASE Hum database “File” or “Console” k alternate main use kartay han . Database say jab bhi data fetch karna hota hai hamain aik cost deni parti hai jo “File” k case main nai deni parti but file is not efficient or protected way . Jab bhi hum database say ko apne program main include karain gay hamain database create karni pare gi . Main yahain Visual Stdio 2012 use kar raha hun aye daikhtay hain k yey sara kam kaise huga. STEPS 1- Open Visual Studio 2012
  • 2. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 2 2- Create new project 3- Select Visual C# and Console Application and named it
  • 3. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 3 After , this screen will appear 4- Now right click on name space that is on right side that is name of your application Add => New Item => Data => Service based Database and named it with extension .mdf
  • 4. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 4
  • 5. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 5 5- Now this appear on main screen 6- Now create table in it and insert some data Double click on database name in server explorer => right click on table => add new table => Fill table property and named it finally and some data by click on table name => show table data
  • 6. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 6
  • 7. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 7 Ok now create SqlConnection object and pass Path of database You get path of your database by double click on your database its properties was shown here you copy the ConnectionString .
  • 8. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 8 In this chapter all students note that following: Database Name : Student Table Name : Stu(Id , Name , Mobile) Now see the code and try to create understanding . Remember out database name is Student.mdf and table name is Stu(Id,Name,Mobile). using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace SalmanMushtaq { class Program { static void Main(string[] args) { string cs = @"Data Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In tegrated Security=True"; SqlConnection con = new SqlConnection(cs); string query = "select * from Stu"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); SqlDataReader dr = cmd.ExecuteReader(); while (dr.Read()) {
  • 9. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 9 Console.Write("Id : " + dr["Id"]); Console.Write("Name : " + dr["Name"]); Console.WriteLine("Mobile No : " + dr["Mobile"]); } con.Close(); } } } Output: Ok selection is complete now INSERTION See code and understand Database before insertion
  • 10. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 10 Database after insertion: Ok let we start the coding and then we show you the Output. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace SalmanMushtaq { class Program { static void Main(string[] args) { string cs = @"Data Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In tegrated Security=True"; SqlConnection con = new SqlConnection(cs); String n, m; int i = 4; // We initialize Id as i=4 because we have three records already // Afterwards you make your primary key AutoIncrement Console.WriteLine("Enter Name"); n = Console.ReadLine(); Console.WriteLine("Enter Mobile Number"); m = Console.ReadLine(); string query = "Insert into Stu(Id,Name,Mobile) Values ('" + i + "','" + n + "','" + m + "')"; SqlCommand cmd = new SqlCommand(query, con); con.Open(); int dr = cmd.ExecuteNonQuery(); if (dr > 0)
  • 11. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 11 Console.WriteLine(dr + " row inserted successfully"); con.Close(); } } } See the output: Our database
  • 12. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 12 Now there is 4 records … Ok I hope you enjoy the database programming Now we insert Record 5 with parameterized query: Let see the code and understand: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace SalmanMushtaq { class Program { static void Main(string[] args) { string cs = @"Data Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In tegrated Security=True"; SqlConnection con = new SqlConnection(cs); String n, m; int i = 5; // We initialize Id as i=5 because we have three records already // Afterwards you make your primary key AutoIncrement Console.WriteLine("Enter Name"); n = Console.ReadLine(); Console.WriteLine("Enter Mobile Number");
  • 13. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 13 m = Console.ReadLine(); string query = "Insert into Stu(Id,Name,Mobile) values(@I , @N, @M)"; // Because we insert data through parameterized so we create SqlParameter object // and add it into Command SqlParameter p1 = new SqlParameter("I",i); SqlParameter p2 = new SqlParameter("N",n); SqlParameter p3 = new SqlParameter("M",m); SqlCommand cmd = new SqlCommand(query, con); // Add parameters cmd.Parameters.Add(p1); cmd.Parameters.Add(p2); cmd.Parameters.Add(p3); con.Open(); int dr = cmd.ExecuteNonQuery(); if (dr > 0) Console.WriteLine(dr + " row inserted successfully"); con.Close(); } } } Output: Ok now see database
  • 14. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 14 You see there are 5 records in a database: Ok now Insertion is complete . Let we start Updation of data in C# (DataBase). Update: See code and understand: Before updation:
  • 15. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 15 Code: // We want to update the record 1 using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace SalmanMushtaq { class Program { static void Main(string[] args) { string cs = @"Data Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In tegrated Security=True"; SqlConnection con = new SqlConnection(cs); String m; int i ; Console.WriteLine("Enter Valid Id"); i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Mobile Number"); m = Console.ReadLine(); string query = "Update Stu set Mobile=@M where Id=@i"; SqlParameter p1 = new SqlParameter("I",i); SqlParameter p2 = new SqlParameter("M",m); SqlCommand cmd = new SqlCommand(query, con);
  • 16. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 16 // Add parameters cmd.Parameters.Add(p1); cmd.Parameters.Add(p2); con.Open(); int dr = cmd.ExecuteNonQuery(); if (dr > 0) Console.WriteLine(dr + " row updated successfully"); else Console.WriteLine("Invalid Id"); con.Close(); } } } After Updation:
  • 17. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 17 Ok updation is complete now we go to Deletion: Delete: We want to delete Record 5 Code: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; namespace SalmanMushtaq { class Program { static void Main(string[] args) { string cs = @"Data Source=(LocalDB)v11.0;AttachDbFilename=E:EADSalmanMushtaqSalmanMushtaqStudent.mdf;In tegrated Security=True"; SqlConnection con = new SqlConnection(cs); String m; int i ; Console.WriteLine("Enter Valid Id");
  • 18. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 18 i = int.Parse(Console.ReadLine()); string query = "Delete from Stu where Id=@i"; SqlParameter p1 = new SqlParameter("I",i); SqlCommand cmd = new SqlCommand(query, con); // Add parameters cmd.Parameters.Add(p1); con.Open(); int dr = cmd.ExecuteNonQuery(); if (dr > 0) Console.WriteLine(dr + " row deleted successfully"); else Console.WriteLine("Invalid Id"); con.Close(); } } } Output: Database:
  • 19. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 19 Ok Students omeed hai app ab tak koi problem nai hui hu gi understanding main . But if you have any problem contact me any time without any hesitation. Salman Mushtaq Mitf12a006@pucit.edu.pk 03337465571 FaceBook: https://www.facebook.com/salman.mushtaq.39 Ok now we start next topic that is DataTable: DataTable: “When we want in-memory database than we use DataTabe , datatable contains some properties like DataColumn , DataRow etc ” . Ok let implement this concept. Hum jab bhi database k sath connectivity kartay hain hamain kuch cost deni parti hai us cost se bachnay k liye hum DataTable (In-Memory) concept use kartay han. Code : Steps;
  • 20. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 20 1: Create DataTable object (Create Table), than columns , than rows than insert data , select data , update data , delete data …… using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace SalmanMushtaq { class Program { static void Main(string[] args) { DataTable Table1 = new DataTable("Table1"); // We have three columns as in Stu(Id,Name,Mobile) DataColumn Id = new DataColumn("Id", typeof(int)); DataColumn Name = new DataColumn("Name", typeof(string)); DataColumn Mobile = new DataColumn("Mobile", typeof(string)); // Add these Columns in datatable Table1.Columns.Add(Id); Table1.Columns.Add(Name); Table1.Columns.Add(Mobile); // Every table must have primary key so now we make Id as primary key Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be Primary key // will be composite // If we want to make primary key as auto Increamet than use this below code that is in comments // Id.AutoIncrement = true; // Id.AutoIncrementSeed = 1; // kahain say start hu // Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu // we cannot make primary key as auto increament // Add Data DataRow r1 = Table1.NewRow(); // Make a new row in table string n, m; int i = 1; Console.WriteLine("Enter Id"); i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Name"); n = Console.ReadLine(); Console.WriteLine("Enter Mobile"); m = Console.ReadLine(); // Now add row into table r1["Id"] = i;
  • 21. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 21 r1["Name"] = n; r1["Mobile"] = m; Table1.Rows.Add(r1); //Select data // We can select data though row index that is start from 0 // DataRow r = Table1.Rows[0]; // We can select data through primary key // DataRow r = Table1.Rows.Find(PrimaryKey); // We can select data through some criteria // DataRow[] r = Table1.Select("Name like '%Fallen'"); // We can select data through some selection creteria DataRow[] row = Table1.Select("Name like 'Salman%'"); foreach (DataRow r in row) { Console.WriteLine("Id is : " + r["Id"]); Console.WriteLine("Name is : " + r["Name"]); Console.WriteLine("Mobile is : " + r["Mobile"]); } } } } Output: Ok this is Insertion and Selection now Updation
  • 22. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 22 Update DataTable: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace SalmanMushtaq { class Program { static void Main(string[] args) { DataTable Table1 = new DataTable("Table1"); // We have three columns as in Stu(Id,Name,Mobile) DataColumn Id = new DataColumn("Id", typeof(int)); DataColumn Name = new DataColumn("Name", typeof(string)); DataColumn Mobile = new DataColumn("Mobile", typeof(string)); // Add these Columns in datatable Table1.Columns.Add(Id); Table1.Columns.Add(Name); Table1.Columns.Add(Mobile); // Every table must have primary key so now we make Id as primary key Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be Primary key // will be composite // If we want to make primary key as auto Increamet than use this below code that is in comments // Id.AutoIncrement = true; // Id.AutoIncrementSeed = 1; // kahain say start hu // Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu // we cannot make primary key as auto increament // Add Data DataRow r1 = Table1.NewRow(); // Make a new row in table string n, m; int i = 1; Console.WriteLine("Enter Id"); i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Name"); n = Console.ReadLine(); Console.WriteLine("Enter Mobile"); m = Console.ReadLine(); // Now add row into table r1["Id"] = i; r1["Name"] = n; r1["Mobile"] = m;
  • 23. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 23 Table1.Rows.Add(r1); foreach (DataRow r in Table1.Rows) { Console.WriteLine("Id is : " + r["Id"]); Console.WriteLine("Name is : " + r["Name"]); Console.WriteLine("Mobile is : " + r["Mobile"]); } int pk; string mob; Console.WriteLine("Enter Id"); pk = int.Parse(Console.ReadLine()); DataRow urow = Table1.Rows.Find(pk); Console.WriteLine("Enter New Mobile number"); mob = Console.ReadLine(); urow["Mobile"] = mob; Console.WriteLine("-------------"); Console.WriteLine("Update data"); foreach (DataRow r in Table1.Rows) { Console.WriteLine("Id is : " + r["Id"]); Console.WriteLine("Name is : " + r["Name"]); Console.WriteLine("Mobile is : " + r["Mobile"]); } } } } Output:
  • 24. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 24 Ok now we want to delete some data : Delete DataTable: using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Data.SqlClient; using System.Data; namespace SalmanMushtaq { class Program { static void Main(string[] args) { DataTable Table1 = new DataTable("Table1"); // We have three columns as in Stu(Id,Name,Mobile) DataColumn Id = new DataColumn("Id", typeof(int)); DataColumn Name = new DataColumn("Name", typeof(string)); DataColumn Mobile = new DataColumn("Mobile", typeof(string)); // Add these Columns in datatable Table1.Columns.Add(Id); Table1.Columns.Add(Name); Table1.Columns.Add(Mobile);
  • 25. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 25 // Every table must have primary key so now we make Id as primary key Table1.PrimaryKey = new DataColumn[] { Id}; // We use array because may be Primary key // will be composite // If we want to make primary key as auto Increamet than use this below code that is in comments // Id.AutoIncrement = true; // Id.AutoIncrementSeed = 1; // kahain say start hu // Id.AutoIncrementStep = 1; // Har bar kitney ka izafa hu // we cannot make primary key as auto increament // Add Data DataRow r1 = Table1.NewRow(); // Make a new row in table string n, m; int i = 1; Console.WriteLine("Enter Id"); i = int.Parse(Console.ReadLine()); Console.WriteLine("Enter Name"); n = Console.ReadLine(); Console.WriteLine("Enter Mobile"); m = Console.ReadLine(); // Now add row into table r1["Id"] = i; r1["Name"] = n; r1["Mobile"] = m; Table1.Rows.Add(r1); foreach (DataRow r in Table1.Rows) { Console.WriteLine("Id is : " + r["Id"]); Console.WriteLine("Name is : " + r["Name"]); Console.WriteLine("Mobile is : " + r["Mobile"]); } int pk; Console.WriteLine("Enter Id"); pk = int.Parse(Console.ReadLine()); // Delete through index //Table1.Rows.RemoveAt(0); // Delete through primary key DataRow drow = Table1.Rows.Find(pk); Table1.Rows.Remove(drow); Console.WriteLine("------------------"); foreach (DataRow r in Table1.Rows) { Console.WriteLine("Id is : " + r["Id"]); Console.WriteLine("Name is : " + r["Name"]); Console.WriteLine("Mobile is : " + r["Mobile"]);
  • 26. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 26 } } } } Output : You note that after --------------- line there is no data but there is code for print data this is because the data will be deleted. Ok Datable is complete Now we move to our next topic that is DataRelation or Dataset but before doing this we do DataAdapter. DataAdapter: Ok hamain pata hai k DataTable temporary hota hai jaise hi execution end hoti hai memory end hu jati hai jo us ko RAM main allocate hui hoti hai lehaza DataTable tu in-memory table hai lehaza wo bhi khatam hu jata hai , tu kiya ab hum har bar data insert karain gay aur phir koi calculation karain gay nai , hum aysa karain gay k in memory datatabe main data database say fill kar lain gay is ka faida yey hug a k hamain database k sath connectivity sirf aik bar karni paray gi , aur baqi kam in memory tables say hu jae ga , Is kam k liye hum DataAdapter use kartay hain .
  • 27. Database in C# By Salman Mushtaq Mitf12a006@pucit.edu.pk Page 27 DataAdapter k kuch methods hain 1. Fill 2. Update Jab bhi data fill karna hug a hum fill ka method call karain gay with select query Aur baqi tamam queries(update,delete,insert) k liye update ka function call karain gay.