27
Database in C# By Salman Mushtaq [email protected] 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 By Salman Mushtaq

Embed Size (px)

Citation preview

Page 1: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 2: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] Page 2

2- Create new project

3- Select Visual C# and Console Application and named it

Page 3: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 4: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] Page 4

Page 5: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 6: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] Page 6

Page 7: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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 .

Page 8: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:\EAD\SalmanMushtaq\SalmanMushtaq\Student.mdf;Integrated 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()) {

Page 9: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 10: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:\EAD\SalmanMushtaq\SalmanMushtaq\Student.mdf;Integrated 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)

Page 11: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] Page 11

Console.WriteLine(dr + " row inserted successfully"); con.Close(); } } }

See the output:

Our database

Page 12: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:\EAD\SalmanMushtaq\SalmanMushtaq\Student.mdf;Integrated 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");

Page 13: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 14: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:

Page 15: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:\EAD\SalmanMushtaq\SalmanMushtaq\Student.mdf;Integrated 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);

Page 16: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:

Page 17: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:\EAD\SalmanMushtaq\SalmanMushtaq\Student.mdf;Integrated Security=True"; SqlConnection con = new SqlConnection(cs); String m; int i ; Console.WriteLine("Enter Valid Id");

Page 18: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:

Page 19: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

[email protected]

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;

Page 20: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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;

Page 21: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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

Page 22: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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;

Page 23: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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:

Page 24: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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);

Page 25: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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"]);

Page 26: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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 .

Page 27: Database By Salman Mushtaq

Database in C# By Salman Mushtaq

[email protected] 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.