0% found this document useful (0 votes)
19 views

C-Net 8.0-601-800

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views

C-Net 8.0-601-800

Uploaded by

Niranjan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 200

C#.NET 8.

C# – Console - System.IO
Namespace

Introduction to "System.IO" namespace


• The “System.IO” namespace provides a set of classes to manipulate files and folders in the
hard disk.

List of important classes in System.IO namespace:


1. System.IO.FileInfo

2. System.IO.DirectoryInfo

3. System.IO.File

4. System.IO.Directory

5. System.IO.FileStream

6. System.IO.StreamWriter

7. System.IO.StreamReader

D. Harsha Vardhan (.NET Expert) P a g e 601 | 1583


C#.NET 8.0

The “System.IO.FileInfo” class

System.IO.FileInfo class
• The “FileInfo” is a class in “System.IO” namespace.

• The “FileInfo” class’s object represents a file in the harddisk.

• The “FileInfo” class is used to manipulate a file in the harddisk.

Steps for development of “FileInfo” class:


• Import the namespace:

o using System.IO;

• Create a reference variable:

o FileInfo referencevariable;

• Create an object:

o referencevariable = new FileInfo( “file path” );

• Set properties:

o referencevariable.property = value ;

• Call method:

o referencevariable.methodname ();

D. Harsha Vardhan (.NET Expert) P a g e 602 | 1583


C#.NET 8.0

Properties of “FileInfo” class:


Sl. Property Description
No

1 DirectoryName Represents the current file’s location’s full path.

Syntax: referencevariable.DirectoryName

2 Name Represents only name of the file with extension (without path).

Syntax: referencevariable.Name

3 Extension Represents file extension of current file.

Syntax: referencevariable.Extension

4 FullName Represents full path of the current file.

Syntax: referencevariable.FullName

5 Exists Represents whether the current file exists or not. It returns a Boolean
value.

True: The file exists

False: The file not exists

Syntax: referencevariable.Exists

6 Length Represents file size (no. of bytes).

Syntax: referencevariable.Length

7 CreationTime Represents the date and time of file creation.

Syntax: referencevariable.CreationTime

8 LastAccessTime Represents the date and time of file access.

Syntax: referencevariable.LastAccessTime

9 LastWriteTime Represents the date and time of file last modification.

Syntax: referencevariable.LastWriteTime

D. Harsha Vardhan (.NET Expert) P a g e 603 | 1583


C#.NET 8.0

10 Attributes Represents the attributes of the current file.

Syntax: referencevariable.Attributes

11 IsReadOnly Represents whether the current file is readonly or not.

Syntax: referencevariable.IsReadOnly

Constructors of “FileInfo” class:


Sl. Constructor Description
No

1 FileInfo() Initializes the file path.

Syntax: new FileInfo(string FilePath)

Methods of “FileInfo” class:


Sl. Method Description
No

1 CopyTo() Copies the current file into the specified destination path.

It is equal to “copy and paste”.

Syntax: referencevariable.CopyTo(string DestinationFilePath)

2 Delete() Deletes the current file.

Syntax: referencevariable.Delete()

3 MoveTo() Movies the current file into the specified destination path.

It is equal to “cut and paste”.

Syntax: referencevariable.MoveTo(string DestinationFilePath)

D. Harsha Vardhan (.NET Expert) P a g e 604 | 1583


C#.NET 8.0

The “System.IO.FileInfo” class - Example

Creating Project
• Create the following folders and files:

o C:\CSharp

▪ Sample.pdf

• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “FileInfoExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “FileInfoExample”.

• Click on OK.

Program.cs
//Note: Create "C:\CSharp\sample.txt"

using System;
using System.IO;

namespace namespace1
{
class Program
{
static void Main()
{

D. Harsha Vardhan (.NET Expert) P a g e 605 | 1583


C#.NET 8.0

FileInfo f;
f = new FileInfo(@"c:\CSharp\sample.txt");
Console.WriteLine("Exists: " + f.Exists);

if (f.Exists)
{
Console.WriteLine("Full name: " + f.FullName);
Console.WriteLine("Name: " + f.Name);
Console.WriteLine("Directory name: " + f.DirectoryName);
Console.WriteLine("Extension: " + f.Extension);
Console.WriteLine("Creation date and time: " + f.CreationTime);
Console.WriteLine("Modification date and time: " +
f.LastWriteTime);
Console.WriteLine("Access date and time: " + f.LastAccessTime);
Console.WriteLine("Length: " + f.Length + " bytes");
}
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

It shows the file details as above.

D. Harsha Vardhan (.NET Expert) P a g e 606 | 1583


C#.NET 8.0

The “System.IO.DirectoryInfo” class


• The “DirectoryInfo” is a class in “System.IO” namespace.

• The “DirectoryInfo” class’s object represents a folder (directory) in the harddisk.

• The “DirectoryInfo” class is used to manipulate a folder (directory) in the harddisk.

Steps for development of “DirectoryInfo” class:


• Import the namespace:

o using System.IO;

• Create a reference variable:

o DirectoryInfo referencevariable;

• Create an object:

o referencevariable = new DirectoryInfo( “folder path” );

• Set properties:

o referencevariable.property = value ;

• Call method:

o referencevariable.methodname ();

D. Harsha Vardhan (.NET Expert) P a g e 607 | 1583


C#.NET 8.0

Properties of “DirectoryInfo” class:


Sl. Property Description
No

1 Parent.FullName Represents the current folder’s parent folder’s full path.

Syntax: referencevariable.Parent.FullName

2 Name Represents only name of the folder (without parent folder’s path).

Syntax: referencevariable.Name

3 FullName Represents full path of the current folder.

Syntax: referencevariable.FullName

4 Root.FullName Represents full path of the root folder of the current folder.

Syntax: referencevariable.Root.FullName

5 Exists Represents whether the current folder exists or not. It returns a


Boolean value.

True: The folder exists

False: The folder not exists

Syntax: referencevariable.Exists

6 CreationTime Represents the date and time of folder creation.

Syntax: referencevariable.CreationTime

7 LastAccessTime Represents the date and time of folder access.

Syntax: referencevariable.LastAccessTime

8 LastWriteTime Represents the date and time of folder last modification.

Syntax: referencevariable.LastWriteTime

9 Attributes Represents the attributes of the current folder.

Syntax: referencevariable.Attributes

D. Harsha Vardhan (.NET Expert) P a g e 608 | 1583


C#.NET 8.0

Constructors of “DirectoryInfo” class:


Sl. Constructor Description
No

1 DirectoryInfo() Initializes the folder path.

Syntax: new DirectoryInfo(string FolderPath)

Methods of “DirectoryInfo” class:


Sl. Method Description
No

1 Delete() Deletes the current folder, if it is empty.

If the current folder is not empty, it throws an exception


automatically.

Syntax: referencevariable.Delete()

2 Delete(true) Deletes the current folder, including all of its files and sub
folders.

Syntax: referencevariable.Delete(true)

Warning: This action is permanent. It is impossible to undo this


action. Check the folder path before running the program.

3 MoveTo() Movies the current folder into the specified destination path.

It is equal to “cut and paste”.

Note: The destination folder path should be in the same drive.


Ex: C: drive

Syntax: referencevariable.MoveTo(string
DestinationFolderPath)

D. Harsha Vardhan (.NET Expert) P a g e 609 | 1583


C#.NET 8.0

4 CreateSubdirectory() Creates a new folder with specified name.

Syntax: referencevariable.CreateSubdirectory(string
newfoldername)

5 GetFiles() Returns the list of files of the current folder, as an array of


FileInfo[].

Syntax: referencevariable.GetFiles()

6 GetDirectories() Returns the list of sub directories of the current folder, as an


array of DirectoryInfo[].

Syntax: referencevariable.GetDirectories()

The “System.IO.DirectoryInfo” class - Example

Creating Project
• Create the following folders and files:

o C:\CSharp

▪ sample

• firstfolder (folder)

• secondfolder (folder)

• thirdfolder (folder)

• New Text Document.txt

• New Microsoft Word Document.docx

• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 610 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “DirectoryInfoExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DirectoryInfoExample”.

• Click on OK.

Program.cs
using System;
using System.IO;

namespace namespace1
{
class Program
{
static void Main()
{
DirectoryInfo d;
d = new DirectoryInfo(@"c:\CSharp\myfolder");
Console.WriteLine("Exists: " + d.Exists);

if (d.Exists)
{
Console.WriteLine("Full name: " + d.FullName);
Console.WriteLine("Name: " + d.Name);
Console.WriteLine("Directory name: " + d.Parent);
Console.WriteLine("Creation date and time: " + d.CreationTime);
Console.WriteLine("Modification date and time: " +
d.LastWriteTime);
Console.WriteLine("Access date and time: " + d.LastAccessTime);

Console.WriteLine("\nFiles:");
FileInfo[] files = d.GetFiles();
for (int i = 0; i < files.Length; i++)
{

D. Harsha Vardhan (.NET Expert) P a g e 611 | 1583


C#.NET 8.0

Console.WriteLine(files[i].FullName);
}

Console.WriteLine("\nSub directories:");
DirectoryInfo[] directories = d.GetDirectories();
for (int i = 0; i < directories.Length; i++)
{
Console.WriteLine(directories[i].FullName);
}
}
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

It shows the folder details as above.

D. Harsha Vardhan (.NET Expert) P a g e 612 | 1583


C#.NET 8.0

The “System.IO.Directory” class


• The “Directory” is a class in “System.IO” namespace.

• The “Directory” class is a static class, which provides a set of static methods to manipulate

folders.

Steps for development of “Directory” class:


• Import the namespace:

o using System.IO;

• Call any static method:

o Directory.method ();

Methods of “Directory” class:


Sl. Method Description
No

1 Exists() Checks whether the folder exists or not.

True: The folder exists.

False: The folder not exists

Syntax: Directory.Exists(string FolderPath)

2 CreateDirectory() Create the specified folder and returns corresponding DirectoryInfo’s


object.

Syntax: Directory.CreateDirectory(string FolderPath)

D. Harsha Vardhan (.NET Expert) P a g e 613 | 1583


C#.NET 8.0

3 Delete() Deletes the specified folder permanently, including all of its sub folders
and files in it.

Syntax: Directory.Delete(string FolderPath, true)

Warning: This action is permanent. It is impossible to undo this action.


Check the folder path before running the program.

4 Move() Moves the specified source folder into the specified destination
location.

Rule: Both source and destination location should be in the same drive.
Ex: C: drive

Syntax: Directory.Move(string SourceFolderPath, string


DestinationFolderPath)

The “System.IO.Directory” class - Example

Creating Project
• Create the following folders:

o C:\CSharp

▪ Sample (folder)

• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

D. Harsha Vardhan (.NET Expert) P a g e 614 | 1583


C#.NET 8.0

• Type the project name as “DirectoryExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DirectoryExample”.

• Click on OK.

Program.cs
using System;
using System.IO;

namespace DirectoryExample
{
class Program
{
static void Main()
{
if (Directory.Exists(@"c:\folder1") == true)
{
Directory.Delete(@"C:\folder1", true);
}
if (Directory.Exists(@"c:\folder2") == true)
{
Directory.Delete(@"C:\folder2", true);
}

Directory.CreateDirectory(@"C:\folder1");
Console.WriteLine("folder1 created");
Console.WriteLine("folder1 exists: " + Directory.Exists(@"C:\folder1"));
//Output: True

Directory.Delete(@"C:\folder1");
Console.WriteLine("folder1 deleted");
Console.WriteLine("folder1 exists: " + Directory.Exists(@"C:\folder1"));
//Output: False

D. Harsha Vardhan (.NET Expert) P a g e 615 | 1583


C#.NET 8.0

Directory.CreateDirectory(@"C:\folder1");
Console.WriteLine("folder1 created");

Directory.Move(@"C:\folder1", @"C:\folder2");
Console.WriteLine("folder1 moved as folder2");

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 616 | 1583


C#.NET 8.0

The “System.IO.File” class

System.IO.File class
• The “File” is a class in “System.IO” namespace.

• The “File” class is a static class, which provides a set of static methods to manipulate files.

Steps for development of “File” class:


• Import the namespace:

o using System.IO;

• Call any static method:

o File.method ();

Methods of “File” class:


Sl. Method Description
No

1 Exists() Checks whether the file exists or not.

True: The file exists.

False: The file not exists

Syntax: File.Exists(string FilePath)

2 Create() Create the specified file and returns corresponding FileStream’s object.

Syntax: File.Create(string FilePath)

D. Harsha Vardhan (.NET Expert) P a g e 617 | 1583


C#.NET 8.0

3 Delete() Deletes the specified file permanently.

Syntax: File.Delete(string FilePath)

Warning: This action is permanent. It is impossible to undo this action. Check


the file path before running the program.

4 Move() Moves the specified source file into the specified destination location.

Syntax: File.Move(string SourceFilePath, string DestinationFilePath)

5 Copy() Copies the specified source file into the specified destination location.

Syntax: File.Copy(string SourceFilePath, string DestinationFilePath)

The “System.IO.File” class - Example

Creating Project
• Create the following folders and files:

o C:\CSharp

• Open Visual Studio 2019. Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “FileExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “FileExample”. Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 618 | 1583


C#.NET 8.0

Program.cs
using System;
using System.IO;

namespace FileExample
{
class Program
{
static void Main()
{
if (Directory.Exists(@"c:\folder1") == true)
{
Directory.Delete(@"c:\folder1", true);
}

Directory.CreateDirectory(@"c:\folder1");
Console.WriteLine("Folder created");

File.Create(@"c:\folder1\file1.txt").Close();
Console.WriteLine("File created");

File.Copy(@"c:\folder1\file1.txt", @"c:\folder1\file2.txt");
Console.WriteLine("File created");

File.Move(@"c:\folder1\file2.txt", @"c:\folder1\file3.txt");
Console.WriteLine("File moved");

Console.WriteLine("File exists: " + File.Exists(@"c:\folder1\file3.txt"));


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 619 | 1583


C#.NET 8.0

Output

D. Harsha Vardhan (.NET Expert) P a g e 620 | 1583


C#.NET 8.0

The “System.IO.FileStream” class


• The “FileStream” is a class in “System.IO” namespace.

• The “FileStream” class is used to write data to a file (or) read data from an existing file in
byte[ ] format.

• But in fact, it is difficult to deal with byte[ ]. That’s why, often we use StreamWriter or
StreamReader to perform file reading or writing operations.

• “FileStream” is useful while working with “StreamWriter” or “StreamReader”.

• “FileStream” is a child class of a parent class called “Stream”.

• “FileStream” supports two modes majorly:

o “Create” mode: Used to create a new file and write data into the new file.

o “Read” mode: Used to read data from an existing file.

Steps for development of “FileStream” class (Create mode):


• Import the namespace:

o using System.IO;

• Create a reference variable:

o FileStream referencevariable;

• Create an object:

o referencevariable = new FileStream( “file path”, FileMode.Create, FileAccess.Write );

D. Harsha Vardhan (.NET Expert) P a g e 621 | 1583


C#.NET 8.0

Steps for development of “FileStream” class (Open mode):


• Import the namespace:

o using System.IO;

• Create a reference variable:

o FileStream referencevariable;

• Create an object:

o referencevariable = new FileStream( “file path”, FileMode.Open, FileAccess.Read );

D. Harsha Vardhan (.NET Expert) P a g e 622 | 1583


C#.NET 8.0

The “System.IO.StreamWriter” class

System.IO.StreamWriter class
• The “StreamWriter” is a class in “System.IO” namespace.

• The “StreamWriter” class is used to write data to a new / existing file in text format.

• “StreamWriter” is usually used in combination with “FileStream”.

Steps for development of “StreamWriter” class:


• Import the namespace:

o using System.IO;

• Create a reference variable:

o StreamWriter referencevariable;

• Create an object:

o referencevariable = new StreamWriter( file stream object here );

• Write data to file:

o referencevariable.Write (string content);

• Close the file:

o referencevariable.Close ();

D. Harsha Vardhan (.NET Expert) P a g e 623 | 1583


C#.NET 8.0

The “System.IO.StreamWriter” class - Example

Creating Project
• Create the following folder:

o C:\CSharp

• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “StreamWriterExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “StreamWriterExample”.

• Click on OK.

Program.cs
//city.txt
using System;
using System.IO;

namespace namespace1
{
class Program
{
static void Main()
{
//delete the file, if it already exists
FileInfo f = new FileInfo(@"c:\CSharp\file1.txt");
if (f.Exists == true)
f.Delete();

//create the file


FileStream fs = new FileStream(@"c:\CSharp\file1.txt",
FileMode.Create, FileAccess.Write);

D. Harsha Vardhan (.NET Expert) P a g e 624 | 1583


C#.NET 8.0

//write data to the file


StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("Hai");
sw.WriteLine("Hello");
sw.WriteLine("How are you");
//close the file
sw.Close();
Console.WriteLine("Written");
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

The file will be created at “C:\Sharp\sample.txt”.

D. Harsha Vardhan (.NET Expert) P a g e 625 | 1583


C#.NET 8.0

The “System.IO.StreamReader” class

System.IO.StreamReader class
• The “StreamReader” is a class in “System.IO” namespace.

• The “StreamReader” class is used to read data from an existing file in text format.

• “StreamReader” is usually used in combination with “FileStream”.

Steps for development of “StreamReader” class:


• Import the namespace:

o using System.IO;

• Create a reference variable:

o StreamReader referencevariable;

• Create an object:

o referencevariable = new StreamReader( file stream object here );

• Read complete content of the file:

o string variablename = referencevariable.ReadToEnd( );

• Close the file:

o referencevariable.Close( );

D. Harsha Vardhan (.NET Expert) P a g e 626 | 1583


C#.NET 8.0

The “System.IO.StreamReader” class - Example

Creating Project
• Create the following folder:

o C:\CSharp

• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “StreamReaderExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “StreamReaderExample”.

• Click on OK.

Program.cs
//city.txt
using System;
using System.IO;

namespace namespace1
{
class Program
{
static void Main()
{
//check the file exists or not
FileInfo f = new FileInfo(@"c:\CSharp\file1.txt");
if (f.Exists == true)
{
//open the file

D. Harsha Vardhan (.NET Expert) P a g e 627 | 1583


C#.NET 8.0

FileStream fs = new FileStream(@"c:\CSharp\file1.txt",


FileMode.Open, FileAccess.Read);

//read the file


StreamReader sr = new StreamReader(fs);
string s = sr.ReadToEnd();

//close the file


sr.Close();
Console.WriteLine(s);
}
else
{
Console.WriteLine("File not found");
}
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

It shows content from “C:\CSharp\sample.txt” file.

D. Harsha Vardhan (.NET Expert) P a g e 628 | 1583


C#.NET 8.0

C#.NET – Console – ADO.NET

Database Basics
• DBMS (Database Management System): It is a software, which is used to store and

manage databases. Ex: SQL Server, Oracle etc.

• Database: It is a collection of tables. Databases are used to store data permanently.

• Table: It is a collection of rows and columns.

• Column: A field in the table is called as column.

• Row: A record in the table is called as row.

Table Structure

Sl. No Column Name Data Type

1 Column1 Data type 1

2 Column2 Data type 2

3 Column3 Data type 3

Example of Table Structure: Employees

Sl. No Column Name Data Type

1 EmpID Int

2 EmpName Nvarchar(max)

3 Salary decimal

Table: Employees

D. Harsha Vardhan (.NET Expert) P a g e 629 | 1583


C#.NET 8.0

EmpID EmpName Salary

1 Scott 5000

2 Allen 6000

3 Jones 7000

4 John 8000

5 Mark 9000

D. Harsha Vardhan (.NET Expert) P a g e 630 | 1583


C#.NET 8.0

Introduction to ADO.NET

Introduction to ADO.NET
• ADO.NET (ActiveX Data Objects .NET) is a “database technology” or “database
framework”, which is used to connect and interact with databases such as SQL Server,
Oracle, Excel, Access etc.

• ADO.NET is a collection of pre-defined classes.

• ADO.NET can be used in c#.net and asp.net also.

List of pre-defined classes in ADO.NET

• ADO.NET provides the following pre-defined classes.

1. System.Data.SqlClient.SqlConnection

2. System.Data.SqlClient.SqlCommand

3. System.Data.SqlClient.SqlDataReader

4. System.Data.SqlClient.SqlDataAdapter

5. System.Data.SqlClient.SqlParameter

6. System.Data.SqlClient.SqlCommandBuilder

7. System.Data.SqlClient.SqlTransaction

8. System.Data.OleDb.OleDbConnection

9. System.Data.OleDb.OleDbCommand

10. System.Data.OleDb.OleDbDataReader

11. System.Data.OleDb.OleDbDataAdapter

12. System.Data.OleDb.OleDbParameter

13. System.Data.OleDb.OleDbCommandBuilder

14. System.Data.OleDb.OleDbTransaction

D. Harsha Vardhan (.NET Expert) P a g e 631 | 1583


C#.NET 8.0

15. System.Data.DataSet

16. System.Data.DataTable

17. System.Data.DataRow

18. System.Data.DataColumn

19. System.Data.DataView

ADO.NET – “SqlConnection” class

System.Data.SqlClient.SqlConnection
• The “SqlConnection” is a class, which is a member of “System.Data.SqlClient” namespace.

• This class’s object represents a connection to SQL Server database.

Properties of “SqlConnection” class:


Sl. Property Data Type Description
No

1 ConnectionString string Represents details about the connection,


based on which ado.net should establish a
connection with database.

Syntax: referencevariable.ConnectionString
= “connection string here”;

2 State ConnectionState Represents current status of the


connection, whether it is opened or closed.
It is readonly property.

Syntax: referencevariable.State

D. Harsha Vardhan (.NET Expert) P a g e 632 | 1583


C#.NET 8.0

Constructors of “SqlConnection” class:


Sl. Constructor Description
No

1 SqlConnection() Initializes nothing.

Syntax: new SqlConnection();

2 SqlConnection(string Initializes “ConnectionString” property.


ConnectionString)
Syntax: new SqlConnection(“connection string here”);

Methods of “SqlConnection” class:


Sl. Method Return Data Type Description
No

1 Open() void Opens the connection. After opening the connection, SQL
Server listens the requests you made.

Syntax: referencevariable.Open()

2 Close() void Closes the connection. After closing the connection, SQL
Server stops listening the requests you made.

Syntax: referencevariable.Close()

D. Harsha Vardhan (.NET Expert) P a g e 633 | 1583


C#.NET 8.0

Steps for development of “SqlConnection” class:


• Import the namespace:

o using System.Data.SqlClient;

• Create a reference variable:

o SqlConnection referencevariable;

• Create an object:

o referencevariable = new SqlConnection();

• Set connection string:

o referencevariable.ConnectionString = “connection string here”;

• Open the connection:

o referencevariable.Open( );

• Close the connection:

o referencevariable.Close( );

D. Harsha Vardhan (.NET Expert) P a g e 634 | 1583


C#.NET 8.0

Connection Strings for SQL Server


Sl. Type of Description Connection String
No connection

1 Windows The current working “data source=servernamehere ;


Authentication windows username and integrated security=yes; initial
password will be catalog=databasenamehere”
automatically submitted to
SQL Server.

2 SQL Server We can submit SQL Server “data source=servernamehere ; user


Authentication username and password to id=usernamehere ;
SQL Server. password=passwordhere ; initial
catalog=databasenamehere”

D. Harsha Vardhan (.NET Expert) P a g e 635 | 1583


C#.NET 8.0

SqlConnection – Windows Authentication – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 636 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “WindowsAuthExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “WindowsAuthExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace WindowsAuthExample
{
class Program
{
static void Main()
{
//create reference variable
SqlConnection cn;

//create object
cn = new SqlConnection();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";

//calling methods
Console.WriteLine(cn.State); //Output: Closed
cn.Open();
Console.WriteLine(cn.State); //Output: Open
cn.Close();
Console.WriteLine(cn.State); //Output: Closed

D. Harsha Vardhan (.NET Expert) P a g e 637 | 1583


C#.NET 8.0

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 638 | 1583


C#.NET 8.0

SqlConnection – SQL Server Authentication – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

D. Harsha Vardhan (.NET Expert) P a g e 639 | 1583


C#.NET 8.0

• Type the project name as “SqlServerAuthExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “SqlServerAuthExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace SqlServerAuthExample
{
class Program
{
static void Main()
{
//create reference variable
SqlConnection cn;

//create object
cn = new SqlConnection();

//calling properties
cn.ConnectionString = "data source=localhost; user id=sa;
password=123; initial catalog=company";

//calling methods
Console.WriteLine(cn.State); //Output: Closed
cn.Open();
Console.WriteLine(cn.State); //Output: Open
cn.Close();
Console.WriteLine(cn.State); //Output: Closed

Console.ReadKey();
}

D. Harsha Vardhan (.NET Expert) P a g e 640 | 1583


C#.NET 8.0

}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 641 | 1583


C#.NET 8.0

The "SqlCommand" class in ADO.NET


• The “SqlCommand” is a pre-defined class in a namespace called “System.Data.SqlClient”.

• This class’s object is used to execute an SQL statement or stored procedure through
database connection.

• It requires to use SqlConnection class, to connect with database.

• It requires to use SqlParameter class, to pass parameters to DBMS.

Properties of “SqlCommand” class:


Sl. Property Data Type Description
No

1 CommandText string Represents the sql statement or store procedure


name, which has to be executed at the DBMS.

Syntax: referencevariable.CommandText = “sql


statement | stored procedure name here”;

2 Connection SqlConnection Represents the connection object, based on which


the command has to be executed.

Syntax: referencevariable.Connection =
ReferenceVariableOfSqlConnectionClass;

D. Harsha Vardhan (.NET Expert) P a g e 642 | 1583


C#.NET 8.0

3 CommandType CommandType Represents type of the command.

Options: Text | StoredProcedure

a) Text = Represents a command with a


normal SQL statement, such as SELECT |
INSERT | UPDATE | DELETE etc.
b) StoredProcedure = Represents a command
with stored procedure.

Syntax: referencevariable.CommandType =
System.Data.CommandType.Optionhere;

4 Parameters List<SqlParameter> Represents the collection of parameters that are


to be passed to DBMS in order to execute the
command.

Syntax:
referencevariable.Parameters.Add(ReferenceVari
ableOfSqlParameter)

5 Transaction SqlTransaction Represents the transaction, in which the


command is a part.

Syntax: referencevariable.Transaction =
ReferenceVariableOfSqlTransaction;

D. Harsha Vardhan (.NET Expert) P a g e 643 | 1583


C#.NET 8.0

Constructors of “SqlCommand” class:


Sl. Constructor Description
No

1 SqlCommand() Initializes nothing.

Syntax: new SqlCommand();

2 SqlCommand(string Initializes “CommandText” and “Connection” properties.


CommandText,
Syntax: new SqlCommand(“command text here”, cn);
SqlConnection
connection)

Methods of “SqlCommand” class:


Sl. Method Return Data Type Description
No

1 ExecuteScalar() object Executes the SELECT statement and returns


only one result value.

This method requires the connection in


“Open” status.

Syntax: referencevariable.ExecuteScalar()

2 ExecuteReader() SqlDataReader Executes the SELECT statement & creates


and returns an object of SqlDataReader class.

This method requires the connection in


“Open” status.

Syntax: referencevariable.ExecuteReader()

D. Harsha Vardhan (.NET Expert) P a g e 644 | 1583


C#.NET 8.0

3 ExecuteNonQuery() int Executes the INSERT | UPDATE | DELETE


statement & returns the no. of rows affected.

This method requires the connection in


“Open” status.

Syntax:
referencevariable.ExecuteNonQuery()

D. Harsha Vardhan (.NET Expert) P a g e 645 | 1583


C#.NET 8.0

ADO.NET - ExecuteScalar

ExecuteScalar
• “ExecuteScalar” method is used to execute a “SELECT statement” or “stored procedure”

and get the single result value.

Steps for development of “ExecuteScalar” method:


• Import the namespace:

o using System.Data.SqlClient;

• Create reference variables:

o SqlConnection cn;

o SqlCommand cmd;

• Create objects:

o cn = new SqlConnection();

o cmd = new SqlCommand();

• Call properties

o cmd.CommandText = “comamd text here”;

o cmd.Connection = cn;

• Call methods

o cn.Open();

o object variablename = cmd.ExecuteScalar( );

o cn.Close();

D. Harsha Vardhan (.NET Expert) P a g e 646 | 1583


C#.NET 8.0

SqlCommand – ExecuteScalar – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 647 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “ExecuteScalarExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ExecuteScalarExample”. Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace ExecuteScalarExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select EmpName from Employees where
EmpID=1";
cmd.Connection = cn;

/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();

D. Harsha Vardhan (.NET Expert) P a g e 648 | 1583


C#.NET 8.0

cn.Close();
string n = Convert.ToString(obj);
string msg = "Emp Name: " + n;
Console.WriteLine(msg);
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 649 | 1583


C#.NET 8.0

SqlCommand – ExecuteScalar – Example 2

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 650 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “ExecuteScalarExample2”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ExecuteScalarExample2”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace ExecuteScalarExample2
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select count(*) from Employees";
cmd.Connection = cn;

/* call methods */
cn.Open();
object obj = cmd.ExecuteScalar();

D. Harsha Vardhan (.NET Expert) P a g e 651 | 1583


C#.NET 8.0

cn.Close();
string n = Convert.ToString(obj);
Console.WriteLine("Emps Count: " + n);
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 652 | 1583


C#.NET 8.0

ADO.NET – Connection Oriented Model – Introduction


• The “ADO.NET Connection Oriented Model” concept is used to read the data from
database in “record-by-record” (row-by-row) approach.

• ADO.NET sends request to the database server and gets only one record at-a-time. It
stores the current record in an object of “SqlDataReader” class.

• The connection should be in “Open” status, while retrieving data from database.

Advantages of Connection Oriented Model:


• At-a-time ONLY ONE record will be stored in .net application memory (RAM). So it
requires less amount of memory.

Dis-advantages of Connection Oriented Model:


• It is a bit slow-process because of “record-by-record” approach.

• It supports “sequential retrieval of records”. We can’t retrieve a record based on its index.
We can’t retrieve records randomly or in reverse order.

List of classes required for ADO.NET Connection Oriented Model:


1. System.Data.SqlClient.SqlConnection

o Used to connect with SQL Server.

2. System.Data.SqlClient.SqlCommand

o Used to send and execute an SQL statement to SQL Server.

3. System.Data.SqlClient.SqlDataReader

o Used to read records one-by-one.

D. Harsha Vardhan (.NET Expert) P a g e 653 | 1583


C#.NET 8.0

The "SqlDataReader" class in ADO.NET


• The “SqlDataReader” is a pre-defined class in a namespace called “System.Data.SqlClient”.

• This class’s object is used to store a single record, while retrieving data from database in
“ADO.NET Connection Oriented Model”.

• It occupies the memory, which is enough for storing single database record.

• “SqlDataReader” is useful only in “ADO.NET Connection Oriented Model”.

Properties of “SqlDataReader” class:


Sl. Property Data Description
No Type

1 [column index] object Retrieves the column value in the current record, based
on the column index.

Syntax: referencevariable [column index]

2 [“column name”] object Retrieves the column value in the current record, based
on the column name.

Syntax: referencevariable [“column name”]

3 FieldCount int Represents the no. of fields (columns) in the current


record.

Syntax: referencevariable.FieldCount

4 HasRows bool Represents a Boolean value, whether the datareader


object has any rows or not.

Syntax: referencevariable.HasRows

D. Harsha Vardhan (.NET Expert) P a g e 654 | 1583


C#.NET 8.0

Constructors of “SqlDataReader” class:


Sl. Constructor Description
No

No constructors

Methods of “SqlDataReader” class:


Sl. Method Return Data Description
No Type

1 Read() bool Reads the next record into the DataReader.

It returns “true”, if data found.

It returns “false”, if it is reached to end of


records.

Syntax: referencevariable.Read()

2 GetValue(int columnindex) object Returns the value of the specified column in


the current record.

Syntax: referencevariable.GetValue(int
columnindex)

D. Harsha Vardhan (.NET Expert) P a g e 655 | 1583


C#.NET 8.0

ADO.NET – Connection Oriented Model

Steps for development of “ADO.NET Connection Oriented Model”:


• Import the namespace:

o using System.Data.SqlClient;

• Create reference variables:

o SqlConnection cn;

o SqlCommand cmd;

o SqlDataReader dr;

• Create objects:

o cn = new SqlConnection();

o cmd = new SqlCommand();

Note: We are creating an object for “SqlDataReader” class; because it will


be created automatically when we call ExecuteReader() method.

• Call properties

o cmd.CommandText = “comamd text here”;

o cmd.Connection = cn;

• Call methods

o cn.Open();

o dr = cmd.ExecuteReader( );

o dr.Read();

D. Harsha Vardhan (.NET Expert) P a g e 656 | 1583


C#.NET 8.0

o dr[“column name”];

o cn.Close();

ADO.NET Connection Oriented Model – Single Record


– Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

D. Harsha Vardhan (.NET Expert) P a g e 657 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “COMSingleRecordExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “COMSingleRecordExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace COMSingleRecordExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();

/* call properties */

D. Harsha Vardhan (.NET Expert) P a g e 658 | 1583


C#.NET 8.0

cn.ConnectionString = "data source=localhost; integrated


security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where empid=1";
cmd.Connection = cn;

/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2, obj3;

obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine("EmpID: " + eid);
Console.WriteLine("EmpName: " + ename);
Console.WriteLine("Salary: " + sal);
}

cn.Close();
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 659 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 660 | 1583


C#.NET 8.0

ADO.NET Connection Oriented Model – Multiple


Records – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 661 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “COMMultipleRecordsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “COMMultipleRecordsExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace COMMultipleRecordsExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataReader dr;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;

D. Harsha Vardhan (.NET Expert) P a g e 662 | 1583


C#.NET 8.0

/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
while (dr.Read())
{
object obj1, obj2, obj3;
obj1 = dr["EmpID"];
obj2 = dr["EmpName"];
obj3 = dr["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine("EmpID: " + eid + "\nEmpName: " + ename +
"\nSalary: " + sal + "\n");
}
cn.Close();
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 663 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 664 | 1583


C#.NET 8.0

The "SqlParameter" class in ADO.NET

System.Data.SqlClient.SqlParameter
• The “SqlParameter” is a pre-defined class in a namespace called “System.Data.SqlClient”.

• This class’s object represents a parameter (name and value), that is to be passed to DBMS
for execution of command.

• It is useful allover in ADO.NET, such as ExecuteScalar, Connection Oriented Model,


Disconnected Model, Non Query Operations, Stored Procedures, Transactions etc.

Properties of “SqlParamter” class:


Sl. Property Data Type Description
No

1 ParameterName string Represents name of the parameter.

Syntax: referencevariable.ParameterName
= “parameter name here”

2 Value object Represents the actual value of the


parameter.

Syntax: referencevariable.Value

3 DbType DbType Represents the database data type of the


parameter.

Syntax: referencevariable.DbType =
DbType.Optionhere;

D. Harsha Vardhan (.NET Expert) P a g e 665 | 1583


C#.NET 8.0

4 Direction ParameterDirection Represents direction of the parameter,


whether it has to be given to DBMS or has
to be retrieved from DBMS.

Options: Input | Output | InputOutput |


ReturnValue

Syntax: referencevariable.Direction =
ParameterDirection.Optionhere;

Constructors of “SqlParameter” class:


Sl. Constructor Description
No

1 SqlParameter() Initializes nothing.

Syntax: new SqlParameter();

2 SqlParameter(string ParameterName, Initializes ParameterName and Value properties.


object Value)
Syntax: new SqlParameter(“parameter name here”,
value here);

Steps for development of “SqlParameter”:


• Import the namespace:

o using System.Data.SqlClient;

• Create reference variable:

o SqlParameter p;

D. Harsha Vardhan (.NET Expert) P a g e 666 | 1583


C#.NET 8.0

• Create object:

o p = new SqlParameter();

• Call properties

o p.ParameterName = “parameter name here”;

o p.Value = “value here”;

• Add parameter to command:

o cmd.Parameters.Add(p);

D. Harsha Vardhan (.NET Expert) P a g e 667 | 1583


C#.NET 8.0

ADO.NET Connection Oriented Model – SqlParameter


– Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 668 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “COMSqlParameterExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “COMSqlParameterExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace COMSqlParameterExample
{
class Program
{
static void Main()
{
//get empid from keyboard
Console.Write("Emp ID: ");
int n = Convert.ToInt32(Console.ReadLine());

/* create reference variables */


SqlConnection cn;
SqlCommand cmd;
SqlParameter p1;
SqlDataReader dr;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();

D. Harsha Vardhan (.NET Expert) P a g e 669 | 1583


C#.NET 8.0

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees where
empid=@EmpID";
cmd.Connection = cn;
p1.ParameterName = "@EmpID";
p1.Value = n;
cmd.Parameters.Add(p1);

/* call methods */
cn.Open();
dr = cmd.ExecuteReader();
if (dr.Read())
{
object obj1, obj2;

obj1 = dr["EmpName"];
obj2 = dr["Salary"];

string ename;
decimal sal;

ename = Convert.ToString(obj1);
sal = Convert.ToDecimal(obj2);

Console.WriteLine("Emp Name: " + ename);


Console.WriteLine("Salary: " + sal);
}
else
{
Console.WriteLine("No data found");
}
cn.Close();
Console.ReadKey();
}
}

D. Harsha Vardhan (.NET Expert) P a g e 670 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Enter EmpID as “1” and press Enter.

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 671 | 1583


C#.NET 8.0

ADO.NET Disconnected Model


• The “System.Data.SqlClient.SqlDataAdapter” class’s object is used to convert the data
from “result-set” format to “data-set” format.

o Resultset = The data (rows and columns) that is returned from SQL server, after
execution of a SELECT statement.

o DataSet = The data that is stored in .net application memory (RAM) in the form of
objects.

• It loads all records at-once.

• “ADO.NET Disconnected Model” is a concept to retrieve data from database. It is


implemented using “SqlDataAdapter”.

• After loading all records at-once, the connection can be closed. That’s why it is called
“ADO.NET Disconnected Model”.

Advantages of Disconnected Model:


o At-a-time ALL records will be stored (loaded) into .net application memory (RAM).
After that you can disconnect from database. So your app runs faster.

o We can retrieve a record based on the index.

Dis-advantages of Disconnected Model:


o ALL records need to be stored in RAM, up to end of the .net application, so it may
be burden on the RAM, if there are so many records.

D. Harsha Vardhan (.NET Expert) P a g e 672 | 1583


C#.NET 8.0

The “SqlDataAdapter” class


The “SqlDataAdapter” class has following members:

Properties
▪ SqlCommand SelectCommand: It represents the object of SqlCommand class, based on
which the data is to be retrieved from database.

Methods
▪ Fill(DataSet dataset): It executes the SELECT statement, converts the resultset into
dataset and also stores the data in dataset.

▪ Update(DataSet dataset): It updates the changes made in the dataset to the database.

Constructors
▪ SqlDataAdapter(): It initializes nothing.

▪ SqlDataAdapter(SqlCommand SelectCommand): It initializes SelectCommand


property.

D. Harsha Vardhan (.NET Expert) P a g e 673 | 1583


C#.NET 8.0

The “DataSet” class


• DataSet is used in ADO.NET Disconnected Model.

• DataSet temporarily stores the data that is retrieved from database.

• DataSet internally uses XML.

• DataSet can contain multiple tables.

• Every table in DataSet is treated as an object of “System.Data.DataTable” class.

• Every column in DataTable is treated as an object of “System.Data.DataColumn” class.

• Every row in DataTable is treated as an object of “System.Data.DataRow” class.

DataSet - Example

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “DataSetExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DataSetExample”.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 674 | 1583


C#.NET 8.0

Program.cs
/* Expected data:

Categories:
CategoryID CategoryName
1 ab
2 cd

Products:
ProductID ProductName Cost
101 prod1 400
102 prd2 500
103 prd3 600

*/

using System;
using System.Data;

namespace DataSetExample
{
class Program
{
static void Main()
{
//creating dataset
DataSet ds = new DataSet();

//creating 2 tables
DataTable dt1 = new DataTable() { TableName = "Categories" };
DataTable dt2 = new DataTable() { TableName = "Products" };

//creating 2 columns for table1


DataColumn col1 = new DataColumn() { ColumnName = "CategoryID",
DataType = typeof(int) };
DataColumn col2 = new DataColumn() { ColumnName =
"CategoryName", DataType = typeof(string) };

D. Harsha Vardhan (.NET Expert) P a g e 675 | 1583


C#.NET 8.0

//creating 3 columns for table2


DataColumn col3 = new DataColumn() { ColumnName = "ProductID",
DataType = typeof(int) };
DataColumn col4 = new DataColumn() { ColumnName =
"ProductName", DataType = typeof(string) };
DataColumn col5 = new DataColumn() { ColumnName = "Cost",
DataType = typeof(decimal) };

//adding columns to table1


dt1.Columns.Add(col1);
dt1.Columns.Add(col2);

//adding columns to table2


dt2.Columns.Add(col3);
dt2.Columns.Add(col4);
dt2.Columns.Add(col5);

//creating 2 rows for table1


DataRow drow1 = dt1.NewRow();
DataRow drow2 = dt1.NewRow();

//creating 3 rows for table2


DataRow drow3 = dt2.NewRow();
DataRow drow4 = dt2.NewRow();
DataRow drow5 = dt2.NewRow();

//adding rows to table1


dt1.Rows.Add(drow1);
dt1.Rows.Add(drow2);

//adding rows to table2


dt2.Rows.Add(drow3);
dt2.Rows.Add(drow4);
dt2.Rows.Add(drow5);

//adding tables to dataset

D. Harsha Vardhan (.NET Expert) P a g e 676 | 1583


C#.NET 8.0

ds.Tables.Add(dt1);
ds.Tables.Add(dt2);

/************* setting data **************/

//setting data in table1


dt1.Rows[0]["CategoryID"] = 1;
dt1.Rows[0]["CategoryName"] = "ab";
dt1.Rows[1]["CategoryID"] = 2;
dt1.Rows[1]["CategoryName"] = "cd";

//setting data in table2


dt2.Rows[0]["ProductID"] = 101;
dt2.Rows[0]["ProductName"] = "prod1";
dt2.Rows[0]["Cost"] = 400;
dt2.Rows[1]["ProductID"] = 102;
dt2.Rows[1]["ProductName"] = "prod2";
dt2.Rows[1]["Cost"] = 500;
dt2.Rows[2]["ProductID"] = 103;
dt2.Rows[2]["ProductName"] = "prod3";
dt2.Rows[2]["Cost"] = 600;

//getting data from table1


Console.WriteLine(dt1.TableName + ": ");
for (int i = 0; i < dt1.Rows.Count; i++)
{
Console.WriteLine(dt1.Rows[i]["CategoryID"] + ", " +
dt1.Rows[i]["CategoryName"]);
}
Console.WriteLine();

//getting data from table2


Console.WriteLine(dt2.TableName + ": ");
for (int i = 0; i < dt2.Rows.Count; i++)
{

D. Harsha Vardhan (.NET Expert) P a g e 677 | 1583


C#.NET 8.0

Console.WriteLine(dt2.Rows[i]["ProductID"] + ", " +


dt2.Rows[i]["ProductName"] + ", " + dt2.Rows[i]["Cost"]);
}

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 678 | 1583


C#.NET 8.0

ADO.NET Disconnected Model – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 679 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “DisconnectedModelExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DisconnectedModelExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace DisconnectedModelExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";

D. Harsha Vardhan (.NET Expert) P a g e 680 | 1583


C#.NET 8.0

cmd.CommandText = "select * from Employees";


cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];

object obj1, obj2, obj3;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];

int eid;
string ename;
decimal sal;

eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);

Console.WriteLine(eid + ", " + ename + ", " + sal);


}

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 681 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 682 | 1583


C#.NET 8.0

ADO.NET Disconnected Model – Multiple Tables -


Example

Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database departmentsandemployeesdatabase


go

use departmentsandemployeesdatabase
go

create table Departments(


DeptNo int primary key,
DeptName nvarchar(max),
Loc nvarchar(max))
go

create table Employees(


EmpID int primary key,
EmpName varchar(max),
Salary decimal,
DeptNo int references Departments(DeptNo))
go

insert into Departments values(10, 'Acounting', 'New York')


insert into Departments values(20, 'Operations', 'New Delhi')
insert into Departments values(30, 'Sales', 'New Jersy')

insert into Employees values(1, 'Scott', 3000, 10)


insert into Employees values(2, 'Allen', 6500, 10)

D. Harsha Vardhan (.NET Expert) P a g e 683 | 1583


C#.NET 8.0

insert into Employees values(3, 'Jones', 4577, 20)


insert into Employees values(4, 'James', 9500, 20)
insert into Employees values(5, 'Smith', 3345, 30)
insert into Employees values(6, 'Harry', 2500, 30)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MultipleTablesExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MultipleTablesExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace MultipleTablesExample
{
class Program
{
static void Main()

D. Harsha Vardhan (.NET Expert) P a g e 684 | 1583


C#.NET 8.0

{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt1, dt2;
DataRow drow;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from Departments select * from
Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);

/* departments */
Console.WriteLine("Departments:");
dt1 = ds.Tables[0];
int n = 50;
for (int i = 0; i < dt1.Rows.Count; i++)
{
drow = dt1.Rows[i];

object obj1, obj2, obj3;


obj1 = drow["DeptNo"];
obj2 = drow["DeptName"];

D. Harsha Vardhan (.NET Expert) P a g e 685 | 1583


C#.NET 8.0

obj3 = drow["Loc"];

int dno;
string dname;
string loc;

dno = Convert.ToInt32(obj1);
dname = Convert.ToString(obj2);
loc = Convert.ToString(obj3);

Console.WriteLine(dno + ", " + dname + ", " + loc);


}

/* employees */
Console.WriteLine("\nEmployees:");
dt2 = ds.Tables[1];
n += 100;
for (int i = 0; i < dt2.Rows.Count; i++)
{
drow = dt2.Rows[i];

object obj1, obj2, obj3, obj4;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
obj4 = drow["DeptNo"];

int eid;
string ename;
decimal sal;
int dno;

eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);

D. Harsha Vardhan (.NET Expert) P a g e 686 | 1583


C#.NET 8.0

Console.WriteLine(eid + ", " + ename + ", " + sal + ", " + dno);
}

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 687 | 1583


C#.NET 8.0

ADO.NET Disconnected Model – Joins - Example

Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database departmentsandemployeesdatabase


go

use departmentsandemployeesdatabase
go

create table Departments(


DeptNo int primary key,
DeptName nvarchar(max),
Loc nvarchar(max))
go

create table Employees(


EmpID int primary key,
EmpName varchar(max),
Salary decimal,
DeptNo int references Departments(DeptNo))
go

insert into Departments values(10, 'Acounting', 'New York')


insert into Departments values(20, 'Operations', 'New Delhi')
insert into Departments values(30, 'Sales', 'New Jersy')

insert into Employees values(1, 'Scott', 3000, 10)


insert into Employees values(2, 'Allen', 6500, 10)
insert into Employees values(3, 'Jones', 4577, 20)

D. Harsha Vardhan (.NET Expert) P a g e 688 | 1583


C#.NET 8.0

insert into Employees values(4, 'James', 9500, 20)


insert into Employees values(5, 'Smith', 3345, 30)
insert into Employees values(6, 'Harry', 2500, 30)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “JoinsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “JoinsExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace JoinsExample
{
class Program
{
static void Main()
{
/* create reference variables */

D. Harsha Vardhan (.NET Expert) P a g e 689 | 1583


C#.NET 8.0

SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=departmentsandemployeesdatabase";
cmd.CommandText = "select * from employees inner join
departments on employees.deptno=departments.deptno";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];

object obj1, obj2, obj3, obj4, obj5, obj6;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
obj4 = drow["DeptNo"];
obj5 = drow["DeptName"];
obj6 = drow["Loc"];
int eid;
string ename;

D. Harsha Vardhan (.NET Expert) P a g e 690 | 1583


C#.NET 8.0

decimal sal;
int dno;
string dname;
string loc;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
dname = Convert.ToString(obj5);
loc = Convert.ToString(obj6);
Console.WriteLine(eid + ", " + ename + ", " + sal + ", " + dno + ", " + loc);
}
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 691 | 1583


C#.NET 8.0

ADO.NET Non Query - Insertion – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

D. Harsha Vardhan (.NET Expert) P a g e 692 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “InsertionExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “InsertionExample”. Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace InsertionExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees values(10, 'qwerty',
4500)";
cmd.Connection = cn;

D. Harsha Vardhan (.NET Expert) P a g e 693 | 1583


C#.NET 8.0

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

Console.WriteLine(n + " rows inserted");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 694 | 1583


C#.NET 8.0

ADO.NET Non-Query - Updation – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

D. Harsha Vardhan (.NET Expert) P a g e 695 | 1583


C#.NET 8.0

• Type the project name as “UpdationExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “UpdationExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace UpdationExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update Employees set EmpName='asdf',
Salary=8900 where EmpID=1";
cmd.Connection = cn;

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

D. Harsha Vardhan (.NET Expert) P a g e 696 | 1583


C#.NET 8.0

Console.WriteLine(n + " rows updated");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 697 | 1583


C#.NET 8.0

ADO.NET Non-Query - Deletion – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

D. Harsha Vardhan (.NET Expert) P a g e 698 | 1583


C#.NET 8.0

• Type the project name as “DeletionExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DeletionExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace DeletionExample
{
class Program
{
static void Main(string[] args)
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "delete from Employees where EmpID=3";
cmd.Connection = cn;

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

D. Harsha Vardhan (.NET Expert) P a g e 699 | 1583


C#.NET 8.0

Console.WriteLine(n + " rows deleted");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 700 | 1583


C#.NET 8.0

ADO.NET Non Query – Insertion – With SqlParameter


– Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 701 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “InsertionSqlParameterExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “InsertionSqlParameterExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace InsertionSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());

//create reference variables


SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();

D. Harsha Vardhan (.NET Expert) P a g e 702 | 1583


C#.NET 8.0

p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "insert into Employees values(@empid,
@empname, @salary)";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

Console.WriteLine(n + " rows inserted");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 703 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 704 | 1583


C#.NET 8.0

ADO.NET Non-Query – Updation – With SqlParameter


– Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 705 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “UpdationSqlParameterExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “UpdationSqlParameterExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace UpdationSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();
Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());
//create reference variables
SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;
//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();

D. Harsha Vardhan (.NET Expert) P a g e 706 | 1583


C#.NET 8.0

p3 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "update Employees set empname=@empname,
salary=@salary where empid=@empid";
cmd.Connection = cn;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(n + " rows updated");
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 707 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 708 | 1583


C#.NET 8.0

ADO.NET Non-Query – Deletion – With SqlParameter


– Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

D. Harsha Vardhan (.NET Expert) P a g e 709 | 1583


C#.NET 8.0

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “DeletionSqlParameterExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DeletionSqlParameterExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace DeletionSqlParameterExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());

//create reference variables


SqlConnection cn;
SqlCommand cmd;
SqlParameter p1;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";

D. Harsha Vardhan (.NET Expert) P a g e 710 | 1583


C#.NET 8.0

cmd.CommandText = "delete from Employees where empid=@empid";


cmd.Connection = cn;
p1.ParameterName = "@empid";
p1.Value = empId;
cmd.Parameters.Add(p1);
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Console.WriteLine(n + " rows deleted");
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 711 | 1583


C#.NET 8.0

Stored Procedures Calling in ADO.NET

Calling Stored Procedures using ADO.NET


• Stored procedure is a collection of SQL statements that will be stored in database.

• Stored procedures can be called from .net application.

• Stored procedures will be compiled once and executes every time when we call it. This is
called “pre-compilation”.

• Stored procedures improve performance because of pre-compilation.

• Stored procedures support to separate work between database developer and .net
developer in real time.

• Stored procedures are best for performing multiple and complex database operations with
a single database call.

Syntax of creating stored procedure in SQL Server


create procedure procedurename
(@parameter1 datatype, @parameter2 datatype, …)
as begin
code here
end
go

D. Harsha Vardhan (.NET Expert) P a g e 712 | 1583


C#.NET 8.0

ADO.NET Non Query – Insertion – With Stored


Procedures – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go

use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

create procedure InsertEmployee(


@EmpID int,
@EmpName nvarchar(max),
@Salary decimal
)
as begin
insert into Employees values(@EmpID, @EmpName, @Salary)
end
go

D. Harsha Vardhan (.NET Expert) P a g e 713 | 1583


C#.NET 8.0

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “InsertionWithSPExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “InsertionWithSPExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace InsertionWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");
string empName = Console.ReadLine();

D. Harsha Vardhan (.NET Expert) P a g e 714 | 1583


C#.NET 8.0

Console.Write("Enter Salary: ");


decimal sal = Convert.ToDecimal(Console.ReadLine());

//create reference variables


SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "InsertEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

Console.WriteLine(n + " rows inserted");

D. Harsha Vardhan (.NET Expert) P a g e 715 | 1583


C#.NET 8.0

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 716 | 1583


C#.NET 8.0

ADO.NET Non Query – Updation – With Stored


Procedures – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go

use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

create procedure UpdateEmployee(


@EmpID int,
@EmpName nvarchar(max),
@Salary decimal
)
as begin
update Employees set EmpName=@EmpName, Salary=@Salary
where EmpID=@EmpID
end

D. Harsha Vardhan (.NET Expert) P a g e 717 | 1583


C#.NET 8.0

go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “UpdationWithSPExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “UpdationWithSPExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace UpdationWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());
Console.Write("Enter EmpName: ");

D. Harsha Vardhan (.NET Expert) P a g e 718 | 1583


C#.NET 8.0

string empName = Console.ReadLine();


Console.Write("Enter Salary: ");
decimal sal = Convert.ToDecimal(Console.ReadLine());

//create reference variables


SqlConnection cn;
SqlCommand cmd;
SqlParameter p1, p2, p3;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "UpdateEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p2.ParameterName = "@empname";
p3.ParameterName = "@salary";
p1.Value = empId;
p2.Value = empName;
p3.Value = sal;
cmd.Parameters.Add(p1);
cmd.Parameters.Add(p2);
cmd.Parameters.Add(p3);

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

D. Harsha Vardhan (.NET Expert) P a g e 719 | 1583


C#.NET 8.0

Console.WriteLine(n + " rows updated");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 720 | 1583


C#.NET 8.0

ADO.NET Non Query – Deletion – With Stored


Procedures – Example

Creating Database
• Note: Ignore this step, if you have created “company” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go

use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

create procedure DeleteEmployee(


@EmpID int
)
as begin
delete from Employees
where EmpID=@EmpID
end
go

D. Harsha Vardhan (.NET Expert) P a g e 721 | 1583


C#.NET 8.0

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “DeletionWithSPExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “DeletionWithSPExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;
using System.Data;

namespace DeletionWithSPExample
{
class Program
{
static void Main()
{
//accept values from keyboard
Console.Write("Enter Existing EmpID: ");
int empId = Convert.ToInt32(Console.ReadLine());

//create reference variables

D. Harsha Vardhan (.NET Expert) P a g e 722 | 1583


C#.NET 8.0

SqlConnection cn;
SqlCommand cmd;
SqlParameter p1;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "DeleteEmployee";
cmd.Connection = cn;
cmd.CommandType = CommandType.StoredProcedure;
p1.ParameterName = "@empid";
p1.Value = empId;
cmd.Parameters.Add(p1);

//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();

Console.WriteLine(n + " rows deleted");


Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 723 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 724 | 1583


C#.NET 8.0

ADO.NET - Transactions

ADO.NET Transactions
• A transaction is a “collection of database operations such as insertion, deletion and
updation”.

• ADO.NET transactions are used to roll back the previously executed database operations,
when any database operation is failed in a transaction.

• Example: Funds transfer from one bank account to another bank account.

▪ Operation 1: Debit the money from source account.

▪ Operation 2: Credit the money to destination account.

• We use “System.Data.SqlClient.SqlTransaction” class is used to implement ado.net


transactions in the program.

Methods for ADO.NET Transactions:


1. cn.BeginTransaction()

▪ This method creates and starts a new ado.net transaction. It creates and returns an
object for “SqlTransaction” class.

2. transactionReferenceVariable.Commit()

▪ This method will save (fix) the database operations that are executed during the
current transaction.

3. transactionReferenceVariable.RollBack()

▪ This method will rollback (cancel) all the previously executed database operations
during the current transaction.

D. Harsha Vardhan (.NET Expert) P a g e 725 | 1583


C#.NET 8.0

ADO.NET – Transactions - Example

Creating Database
• Note: Ignore this step, if you have created “transactionsdatabase” database already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database transactionsdatabase


go

use transactionsdatabase
go

CREATE TABLE AccountsTable(


AccountNo int primary key,
AccountHolderName nvarchar(40),
Balance decimal)
GO

INSERT INTO AccountsTable VALUES (101, 'scott', 10000)


INSERT INTO AccountsTable VALUES (102, 'allen', 5000)
GO

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

D. Harsha Vardhan (.NET Expert) P a g e 726 | 1583


C#.NET 8.0

• Select “Console Application”.

• Type the project name as “TransactionsExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “TransactionsExample”.

• Click on OK.

Program.cs
using System;
using System.Data.SqlClient;

namespace TransactionsExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlTransaction transaction;
SqlCommand cmd1, cmd2;

//create objects
cn = new SqlConnection();
cmd1 = new SqlCommand();
cmd2 = new SqlCommand();

//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=transactionsdatabase";
cmd1.CommandText = "update AccountsTable set Balance=Balance-
1000 where AccountNo=101";
cmd2.CommandText = "update AccountsTable set
Balance=Balance+1000 were AccountNo=102";
cmd1.Connection = cn;

D. Harsha Vardhan (.NET Expert) P a g e 727 | 1583


C#.NET 8.0

cmd2.Connection = cn;

//call methods
cn.Open();
transaction = cn.BeginTransaction();
cmd1.Transaction = transaction;
cmd2.Transaction = transaction;

try
{
cmd1.ExecuteNonQuery();
Console.WriteLine("First operation done.");

cmd2.ExecuteNonQuery();
Console.WriteLine("Second operation done.");
transaction.Commit(); //save data

Console.WriteLine("Transaction Complete");
}
catch (Exception)
{
transaction.Rollback(); //first operation will be rollback
Console.WriteLine("Rollback done!");
}

cn.Close();
Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 728 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 729 | 1583


C#.NET 8.0

The "OleDb" namespace in ADO.NET

System.Data.OleDb (Object Linking and Embedding Database)


• The “System.Data.OleDb” namespace contains classes like OleDbConnection,
OleDbCommand etc. The usage of these classes are same as SqlConnectoin, SqlCommand
etc.

• The System.Data.OleDb namespace is used to connect and interact with various databases
like Oracle, Excel, Access etc.

Classes in “System.Data.OleDb” namespace

Sl. SqlClient namespace “OleDb” namespace

No (For SQL Server) (For Oracle, Excel, Access)

1 System.Data.SqlClient.SqlConnection System.Data.OleDb.OleDbConnection

2 System.Data.SqlClient.SqlCommand System.Data.OleDb.OleDbCommand

3 System.Data.SqlClient.SqlDataReader System.Data.OleDb.OleDbDataReader

4 System.Data.SqlClient.SqlParameter System.Data.OleDb.OleDbParameter

5 System.Data.SqlClient.SqlDataAdapter System.Data.OleDb.OleDbDataAdapter

6 System.Data.SqlClient.SqlCommandBuilder System.Data.OleDb.OleDbCommandBuilder

7 System.Data.SqlClient.SqlTransaction System.Data.OleDb.OleDbTransaction

8 System.Data.DataSet System.Data.DataSet

9 System.Data.DataTable System.Data.DataTable

10 System.Data.DataRow System.Data.DataRow

11 System.Data.DataColumn System.Data.DataColumn

D. Harsha Vardhan (.NET Expert) P a g e 730 | 1583


C#.NET 8.0

Connection Strings in ADO.NET

Connection string for SQL Server


• "data source=Servernamehere; integrated security=yes; initial
catalog=Databasenamehere"

(or)

• "data source=Servernamehere; user id=Usernamehere; password=Passwordhere; initial


catalog=Databasenamehere"

Connection string for Oracle


• "provider=msdaora.1; user id=Usernamehere; password=Passwordhere"

Connection string for MS Access


• @"provider=Microsoft.Ace.Oledb.12.0; data source=FilePathHere"

Connection string for MS Excel


• @"Provider=Microsoft.ACE.OLEDB.12.0; Data Source=FilePathHere; Extended
Properties='Excel 12.0;HDR=Yes;IMEX=1' "

D. Harsha Vardhan (.NET Expert) P a g e 731 | 1583


C#.NET 8.0

ADO.NET – Oracle - Example

Installing Oracle Database 11g Expression Edition


• Note: Ignore this step, if you have installed “Oracle 11g Express” already.

• You can download Oracle 11g Express Edition at:


http://www.oracle.com/technetwork/database/database-technologies/express-
edition/downloads/index.html

• Open “Oracle 11g Express” folder.

• Double click on “setup.exe”.

• Click on “Yes”.

D. Harsha Vardhan (.NET Expert) P a g e 732 | 1583


C#.NET 8.0

• Please wait while it loads…

• Click on “Next”.

• Click on “I accept the terms in the license agreement”.

D. Harsha Vardhan (.NET Expert) P a g e 733 | 1583


C#.NET 8.0

• Click on “Next”.

• Click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 734 | 1583


C#.NET 8.0

• Enter the password as “123”.

• Enter the confirm password “123”.

• Click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 735 | 1583


C#.NET 8.0

• Click on “Install”.

• Installation may take around 10 minutes.

o Click on OK if it shows one or two errors while installing.

D. Harsha Vardhan (.NET Expert) P a g e 736 | 1583


C#.NET 8.0

• Click on “Finish”.

• Restart the PC.

Creating table in Oracle


• Note: Ignore this step, if you have created “employees” table in Oracle already.

• Go to “Start” – “Oracle 11g Express Edition” – “Run SQL Command Line”.

D. Harsha Vardhan (.NET Expert) P a g e 737 | 1583


C#.NET 8.0

• Type the following script and press Enter.

connect system/123;

D. Harsha Vardhan (.NET Expert) P a g e 738 | 1583


C#.NET 8.0

create table Employees(


EmpID int primary key,
EmpName varchar2(40),
Salary decimal);

insert into Employees values(1, 'scott', 1040);


insert into Employees values(2, 'james', 9821);
insert into Employees values(3, 'jones', 7721);

commit;

D. Harsha Vardhan (.NET Expert) P a g e 739 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “OracleExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “OracleExample”.

• Click on OK.

Program.cs
using System;
using System.Data.OleDb;
using System.Data;

namespace OracleExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

/* create objects */
cn = new OleDbConnection();

D. Harsha Vardhan (.NET Expert) P a g e 740 | 1583


C#.NET 8.0

cmd = new OleDbCommand();


adp = new OleDbDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}

D. Harsha Vardhan (.NET Expert) P a g e 741 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 742 | 1583


C#.NET 8.0

ADO.NET – MS Access - Example

Installing Access Database Engine


• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US

• Additionally, we have to install “Access Database Engine”.

• Note: Ignore this step, if you have installed “Access Database Engine” already.

• You can download “MS Access Database Engine” at: https://www.microsoft.com/en-


in/download/details.aspx?id=13255

• To install “Access Database Engine”, go to “Access Database Engine” folder.

• Double click on “AccessDatabaseEngine”.

• Click on “Yes”.

D. Harsha Vardhan (.NET Expert) P a g e 743 | 1583


C#.NET 8.0

• Check the checkbox “I accept the terms in the License Agreement”.

• Click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 744 | 1583


C#.NET 8.0

• Click on “Install”.

• Installation may take around 1 or 2 minutes.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 745 | 1583


C#.NET 8.0

Creating table in MS Access


• Go to “Start” – “Access 2016”.

• Click on “Blank desktop database”.

• Type the file name as “Database1.accdb”.

• Click on the folder icon and select “C:\CSharp” folder.

D. Harsha Vardhan (.NET Expert) P a g e 746 | 1583


C#.NET 8.0

• Click on OK.

• Click on “Create”.

D. Harsha Vardhan (.NET Expert) P a g e 747 | 1583


C#.NET 8.0

• Right click on “Table1” and click on “Design View”.

• Type the table name as “Employees”.

D. Harsha Vardhan (.NET Expert) P a g e 748 | 1583


C#.NET 8.0

• Click on OK.

• Type the table structure as follows:

• Right click “Employees” and click on “Open”.

D. Harsha Vardhan (.NET Expert) P a g e 749 | 1583


C#.NET 8.0

• Click on “Yes”.

• Type the data as follows:

• Save the file.

• Close “Microsoft Access 2016”.

• Make sure “Database1.accdb” file exist in “C:\CSharp” folder.

D. Harsha Vardhan (.NET Expert) P a g e 750 | 1583


C#.NET 8.0

D. Harsha Vardhan (.NET Expert) P a g e 751 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MSAccessExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MSAccessExample”.

• Click on OK.

Program.cs
using System;
using System.Data.OleDb;
using System.Data;

namespace MSAccessExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

/* create objects */
cn = new OleDbConnection();

D. Harsha Vardhan (.NET Expert) P a g e 752 | 1583


C#.NET 8.0

cmd = new OleDbCommand();


adp = new OleDbDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = @"provider=Microsoft.Ace.Oledb.12.0; data
source=C:\CSharp\Database1.accdb";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}

D. Harsha Vardhan (.NET Expert) P a g e 753 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 754 | 1583


C#.NET 8.0

ADO.NET – MS Excel - Example

Installing Access Database Engine


• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US

• Additionally, we have to install “Access Database Engine”.

• Note: Ignore this step, if you have installed “Access Database Engine” already.

• You can download “MS Access Database Engine” at: https://www.microsoft.com/en-


in/download/details.aspx?id=13255

• To install “Access Database Engine”, go to “Access Database Engine” folder.

• Double click on “AccessDatabaseEngine”.

• Click on “Yes”.

D. Harsha Vardhan (.NET Expert) P a g e 755 | 1583


C#.NET 8.0

• Check the checkbox “I accept the terms in the License Agreement”.

• Click on “Next”.

D. Harsha Vardhan (.NET Expert) P a g e 756 | 1583


C#.NET 8.0

• Click on “Install”.

• Installation may take around 1 or 2 minutes.

• Click on OK.

D. Harsha Vardhan (.NET Expert) P a g e 757 | 1583


C#.NET 8.0

Creating work book in MS Excel


• Go to “Start” – “Excel 2016”.

• Click on “Blank Workbook”.

D. Harsha Vardhan (.NET Expert) P a g e 758 | 1583


C#.NET 8.0

• Type the data as follows:

• Go to “File” – “Save” – “This PC” – “Browse”.

D. Harsha Vardhan (.NET Expert) P a g e 759 | 1583


C#.NET 8.0

• Select the folder as “C:\CSharp”.

• Type the filename as “Book1.xlsx”.

• Click on “Save”.

• Close “Microsoft Excel 2016”.

• Make sure “Book1.xlsx” file exist in “C:\CSharp” folder.

D. Harsha Vardhan (.NET Expert) P a g e 760 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “MSExcelExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “MSExcelExample”.

• Click on OK.

Program.cs
using System;
using System.Data.OleDb;
using System.Data;

namespace MSExcelExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

/* create objects */
cn = new OleDbConnection();

D. Harsha Vardhan (.NET Expert) P a g e 761 | 1583


C#.NET 8.0

cmd = new OleDbCommand();


adp = new OleDbDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=1' ";
cmd.CommandText = "select * from [Sheet1$]";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.WriteLine(eid + ", " + ename + ", " + sal);
}
Console.ReadKey();
}
}
}

D. Harsha Vardhan (.NET Expert) P a g e 762 | 1583


C#.NET 8.0

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 763 | 1583


C#.NET 8.0

ADO.NET – SQL Server to Oracle - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database in SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Installing Oracle Database 11g Expression Edition


• Install “Oracle 11g Express” as shown in the previous example.

• You can download Oracle 11g Express Edition at:


http://www.oracle.com/technetwork/database/database-technologies/express-
edition/downloads/index.html

D. Harsha Vardhan (.NET Expert) P a g e 764 | 1583


C#.NET 8.0

Creating table in Oracle


• Note: Ignore this step, if you have created “employees2” table in Oracle already.

• Go to “Start” – “Oracle 11g Express Edition” – “Run SQL Command Line”.

D. Harsha Vardhan (.NET Expert) P a g e 765 | 1583


C#.NET 8.0

• Type the following script and press Enter.

connect system/123;

create table Employees2(


EmpID int,
EmpName varchar2(40),
Salary decimal);

commit;

D. Harsha Vardhan (.NET Expert) P a g e 766 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “SqlServerToOracleExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “SqlServerToOracleExample”.

• Click on OK.

Program.cs
//Copy data from "SqlServer" to "Oracle"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

namespace SqlServerToOracleExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

D. Harsha Vardhan (.NET Expert) P a g e 767 | 1583


C#.NET 8.0

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];

object obj1, obj2, obj3;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];

int eid;
string ename;
decimal sal;

eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);

InsertIntoOracle(eid, ename, sal);


}

Console.WriteLine(dt.Rows.Count + " records copied");

D. Harsha Vardhan (.NET Expert) P a g e 768 | 1583


C#.NET 8.0

Console.ReadKey();
}

private static void InsertIntoOracle(int eid, string ename, decimal sal)


{
//create reference variables
OleDbConnection cn;
OleDbCommand cmd;

//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();

//calling properties
cn.ConnectionString = "user id=system; password=123;
provider=msdaora.1";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;

//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

D. Harsha Vardhan (.NET Expert) P a g e 769 | 1583


C#.NET 8.0

Note: If any database connection problem, it shows exception (run time error).

Check the data in “Oracle”:

D. Harsha Vardhan (.NET Expert) P a g e 770 | 1583


C#.NET 8.0

ADO.NET – SQL Server to MS Excel - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database in SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees(


EmpID int primary key,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Installing Access Database Engine


• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US

D. Harsha Vardhan (.NET Expert) P a g e 771 | 1583


C#.NET 8.0

• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.

• Note: Ignore this step, if you have installed “Access Database Engine” already.

• You can download “MS Access Database Engine” at: https://www.microsoft.com/en-


in/download/details.aspx?id=13255

Creating work book in MS Excel


• Go to “Start” – “Excel 2016”.

• Click on “Blank Workbook”.

D. Harsha Vardhan (.NET Expert) P a g e 772 | 1583


C#.NET 8.0

• Type the data as follows:

• Go to “File” – “Save” – “This PC” – “Browse”.

D. Harsha Vardhan (.NET Expert) P a g e 773 | 1583


C#.NET 8.0

• Select the folder as “C:\CSharp”.

• Type the filename as “Book2.xlsx”.

• Click on “Save”.

• Close “Microsoft Excel 2016”.

• Make sure “Book2.xlsx” file exist in “C:\CSharp” folder.

D. Harsha Vardhan (.NET Expert) P a g e 774 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “SqlServerToExcelExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “SqlServerToExcelExample”.

• Click on OK.

Program.cs
//Copy data from "SqlServer" to "Excel"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

namespace SqlServerToExcelExample
{
class Program
{
static void Main()
{
/* create reference variables */
SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

D. Harsha Vardhan (.NET Expert) P a g e 775 | 1583


C#.NET 8.0

/* create objects */
cn = new SqlConnection();
cmd = new SqlCommand();
adp = new SqlDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];

object obj1, obj2, obj3;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];

int eid;
string ename;
decimal sal;

eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);

InsertIntoExcel(eid, ename, sal);


}

Console.WriteLine(dt.Rows.Count + " records copied");

D. Harsha Vardhan (.NET Expert) P a g e 776 | 1583


C#.NET 8.0

Console.ReadKey();
}

private static void InsertIntoExcel(int eid, string ename, decimal sal)


{
//create reference variables
OleDbConnection cn;
OleDbCommand cmd;

//create objects
cn = new OleDbConnection();
cmd = new OleDbCommand();

//calling properties
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book2.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=3' ";
cmd.CommandText = string.Format("insert into [Sheet1$] values('{0}',
'{1}', '{2}')", eid, ename, sal);
cmd.Connection = cn;

//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 777 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

• Check the data in “C:\CSharp\Book2.xlsx” file.

D. Harsha Vardhan (.NET Expert) P a g e 778 | 1583


C#.NET 8.0

ADO.NET – Oracle to SQL Server - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go

use company
go

create table Employees2(


EmpID int,
EmpName nvarchar(max),
Salary decimal)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Installing Oracle Database 11g Expression Edition


• Install “Oracle 11g Express” as shown in the previous example.

• You can download Oracle 11g Express Edition at:


http://www.oracle.com/technetwork/database/database-technologies/express-
edition/downloads/index.html

D. Harsha Vardhan (.NET Expert) P a g e 779 | 1583


C#.NET 8.0

Creating table in Oracle


• Note: Ignore this step, if you have created “employees2” table in Oracle already.

• Go to “Start” – “Oracle 11g Express Edition” – “Run SQL Command Line”.

• Type the following script and press Enter.

connect system/123;

D. Harsha Vardhan (.NET Expert) P a g e 780 | 1583


C#.NET 8.0

create table Employees2(


EmpID int,
EmpName varchar2(40),
Salary decimal);

insert into Employees2 values(1, 'scott', 1040);


insert into Employees2 values(2, 'james', 9821);
insert into Employees2 values(3, 'jones', 7721);

commit;

D. Harsha Vardhan (.NET Expert) P a g e 781 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “OracleToSqlServerExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “OracleToSqlServerExample”.

• Click on OK.

Program.cs
//Copy data from "Oracle" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

namespace OracleToSqlServerExample
{
class Program
{
static void Main()
{
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();

D. Harsha Vardhan (.NET Expert) P a g e 782 | 1583


C#.NET 8.0

cn.ConnectionString = "user id=system; password=123;


provider=msdaora.1";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;

adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
object obj1, obj2, obj3;
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
InsertIntoSqlServer(eid, ename, sal);
}
Console.WriteLine(dt.Rows.Count + " records copied");
Console.ReadKey();
}

private static void InsertIntoSqlServer(int eid, string ename, decimal


sal)
{
SqlConnection cn;
SqlCommand cmd;

cn = new SqlConnection();
cmd = new SqlCommand();

D. Harsha Vardhan (.NET Expert) P a g e 783 | 1583


C#.NET 8.0

cn.ConnectionString = "data source=localhost; integrated


security=yes; initial catalog=company";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

Output

Note: If any database connection problem, it shows exception (run time error).

Check the data in “SQL Server”:

D. Harsha Vardhan (.NET Expert) P a g e 784 | 1583


C#.NET 8.0

D. Harsha Vardhan (.NET Expert) P a g e 785 | 1583


C#.NET 8.0

ADO.NET – Excel to SQL Server - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go

use company
go

create table Employees2(


EmpID int,
EmpName nvarchar(max),
Salary decimal)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Installing Access Database Engine


• Install MS Office 2007 or 2010 or 2013 or 2016. You can download MS Office 2016 at:
https://support.office.com/en-us/article/Download-and-install-or-reinstall-Office-365-
Office-2016-or-Office-2013-on-your-PC-or-Mac-4414eaaf-0478-48be-9c42-
23adc4716658?ui=en-US&rs=en-US&ad=US

• Additionally, we have to install “Access Database Engine”, based on the steps explained in
the previous examples.

• Note: Ignore this step, if you have installed “Access Database Engine” already.

D. Harsha Vardhan (.NET Expert) P a g e 786 | 1583


C#.NET 8.0

• You can download “MS Access Database Engine” at: https://www.microsoft.com/en-


in/download/details.aspx?id=13255

Creating Workbook in “Excel”:


• Go to “Start” – “Excel 2016”.

• Click on “Blank Workbook”.

D. Harsha Vardhan (.NET Expert) P a g e 787 | 1583


C#.NET 8.0

• Type the data as follows:

• Go to “File” – “Save” – “This PC” – “Browse”.

D. Harsha Vardhan (.NET Expert) P a g e 788 | 1583


C#.NET 8.0

• Select the folder as “C:\CSharp”.

• Type the filename as “Book1.xlsx”.

• Click on “Save”.

• Close “Microsoft Excel 2016”.

• Make sure “Book1.xlsx” file exist in “C:\CSharp” folder.

D. Harsha Vardhan (.NET Expert) P a g e 789 | 1583


C#.NET 8.0

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “ExcelToSqlServerExample”.

• Type the location as “C:\CSharp”.

• Type the solution name as “ExcelToSqlServerExample”.

• Click on OK.

Program.cs
//Copy data from "Excel" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.Data.OleDb;
using System.Data;

namespace ExcelToSqlServerExample
{
class Program
{
static void Main()
{
/* create reference variables */
OleDbConnection cn;
OleDbCommand cmd;
OleDbDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;

D. Harsha Vardhan (.NET Expert) P a g e 790 | 1583


C#.NET 8.0

/* create objects */
cn = new OleDbConnection();
cmd = new OleDbCommand();
adp = new OleDbDataAdapter();
ds = new DataSet();

/* call properties */
cn.ConnectionString = @"Provider=Microsoft.ACE.OLEDB.12.0; Data
Source=C:\CSharp\Book1.xlsx; Extended Properties='Excel
12.0;HDR=Yes;IMEX=1' ";
cmd.CommandText = "select * from [Sheet1$]";
cmd.Connection = cn;
adp.SelectCommand = cmd;

/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];

object obj1, obj2, obj3;


obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];

int eid;
string ename;
decimal sal;

eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);

InsertIntoSqlServer(eid, ename, sal);


}

D. Harsha Vardhan (.NET Expert) P a g e 791 | 1583


C#.NET 8.0

Console.WriteLine(dt.Rows.Count + " records copied");


Console.ReadKey();
}

private static void InsertIntoSqlServer(int eid, string ename, decimal


sal)
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();

//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = string.Format("insert into Employees2
values({0}, '{1}', {2})", eid, ename, sal);
cmd.Connection = cn;

//calling methods
cn.Open();
cmd.ExecuteNonQuery();
cn.Close();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 792 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

Check the data in “SQL Server”:

D. Harsha Vardhan (.NET Expert) P a g e 793 | 1583


C#.NET 8.0

ADO.NET – SQL Server to File - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees2(


EmpID int,
EmpName nvarchar(max),
Salary decimal)
go

insert into Employees values(1, 'Scott', 4000)


insert into Employees values(2, 'Allen', 5000)
insert into Employees values(3, 'Jones', 6000)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”. Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “SqlServerToFileExample”.

D. Harsha Vardhan (.NET Expert) P a g e 794 | 1583


C#.NET 8.0

• Type the location as “C:\CSharp”.

• Type the solution name as “SqlServerToFileExample”. Click on OK.

Program.cs
//Copy data from "SqlServer" to "File"
using System;
using System.Data.SqlClient;
using System.Data;
using System.Diagnostics;
using System.IO;
namespace SqlServerToFileExample
{
class Program
{
static void Main()
{
//create directory if not exists
if (Directory.Exists(@"C:\CSharp") == false)
{
Directory.CreateDirectory(@"C:\CSharp");
}

//create reference variables


SqlConnection cn;
SqlCommand cmd;
SqlDataAdapter adp;
DataSet ds;
DataTable dt;
DataRow drow;
FileInfo finfo;
FileStream fs;
StreamWriter sw;

//create objects
cn = new SqlConnection();

D. Harsha Vardhan (.NET Expert) P a g e 795 | 1583


C#.NET 8.0

cmd = new SqlCommand();


adp = new SqlDataAdapter();
ds = new DataSet();
finfo = new FileInfo(@"C:\CSharp\Employees.txt");

//delete the file if already exists


if (finfo.Exists == true)
finfo.Delete();

//create objects
fs = new FileStream(@"C:\CSharp\Employees.txt", FileMode.Create,
FileAccess.Write);
sw = new StreamWriter(fs);

//call properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
cmd.CommandText = "select * from Employees2";
cmd.Connection = cn;
adp.SelectCommand = cmd;

//call methods
adp.Fill(ds);

//read data
dt = ds.Tables[0];

//read data from database record-by-record


for (int i = 0; i < dt.Rows.Count; i++)
{
//get values
object obj1, obj2, obj3;
drow = dt.Rows[i];
obj1 = drow["EmpID"];
obj2 = drow["EmpName"];
obj3 = drow["Salary"];
int eid = Convert.ToInt32(obj1);

D. Harsha Vardhan (.NET Expert) P a g e 796 | 1583


C#.NET 8.0

string ename = Convert.ToString(obj2);


double sal = Convert.ToDouble(obj3);
string msg = eid + "," + ename + "," + sal;
//write data to the file
sw.WriteLine(msg);
}

//close the file


sw.Close();

Console.WriteLine("Data has been written to the following file


successfully.\nC:\\CSharp\\Employees.txt");

//open the file in notepad


Process.Start(@"C:\Windows\System32\notepad.exe",
@"C:\CSharp\Employees.txt");

Console.ReadKey();
}
}
}

Running the Project


• Go to “Debug” menu and click on “Start Debugging”.

D. Harsha Vardhan (.NET Expert) P a g e 797 | 1583


C#.NET 8.0

Output

Note: If any database connection problem, it shows exception (run time error).

D. Harsha Vardhan (.NET Expert) P a g e 798 | 1583


C#.NET 8.0

ADO.NET – File to SQL Server - Example

Creating SQL Server Database


• Note: Ignore this step, if you have created “company” database with “Employees2” table in
SQL Server, already.

• Open SQL Server Management Studio. Click on “Connect”.

• Click on “New Query”.

• Type the following code:

create database company


go
use company
go

create table Employees2(


EmpID int,
EmpName nvarchar(max),
Salary decimal)
go

• Click on “Execute” button. It shows “Query executed successfully” in the status bar.

Creating Project
• Open Visual Studio 2019.

• Go to “File” – “New” – “Project”.

• Select “.NET Framework 4.8”.

• Select “Visual C#”.

• Select “Console Application”.

• Type the project name as “FileToSqlServerExample”.

• Type the location as “C:\CSharp”.

D. Harsha Vardhan (.NET Expert) P a g e 799 | 1583


C#.NET 8.0

• Type the solution name as “FileToSqlServerExample”.

• Click on OK.

Program.cs
//Copy data from "File" to "SqlServer"
using System;
using System.Data.SqlClient;
using System.IO;

namespace FileToSqlServerExample
{
class Program
{
static void Main()
{
//create reference variables
SqlConnection cn;
SqlCommand cmd;
FileInfo finfo;
FileStream fs;
StreamReader sr;
SqlParameter p1, p2, p3;

//create objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
p2 = new SqlParameter();
p3 = new SqlParameter();
finfo = new FileInfo(@"C:\CSharp\Employees.txt");

//check whether the file already exists or not


if (finfo.Exists == false)
{
Console.WriteLine("File not exists.");

D. Harsha Vardhan (.NET Expert) P a g e 800 | 1583

You might also like