C-Net 8.0-601-800
C-Net 8.0-601-800
C# – Console - System.IO
Namespace
2. System.IO.DirectoryInfo
3. System.IO.File
4. System.IO.Directory
5. System.IO.FileStream
6. System.IO.StreamWriter
7. System.IO.StreamReader
System.IO.FileInfo class
• The “FileInfo” is a class in “System.IO” namespace.
o using System.IO;
o FileInfo referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
Syntax: referencevariable.DirectoryName
2 Name Represents only name of the file with extension (without path).
Syntax: referencevariable.Name
Syntax: referencevariable.Extension
Syntax: referencevariable.FullName
5 Exists Represents whether the current file exists or not. It returns a Boolean
value.
Syntax: referencevariable.Exists
Syntax: referencevariable.Length
Syntax: referencevariable.CreationTime
Syntax: referencevariable.LastAccessTime
Syntax: referencevariable.LastWriteTime
Syntax: referencevariable.Attributes
Syntax: referencevariable.IsReadOnly
1 CopyTo() Copies the current file into the specified destination path.
Syntax: referencevariable.Delete()
3 MoveTo() Movies the current file into the specified destination path.
Creating Project
• Create the following folders and files:
o C:\CSharp
▪ Sample.pdf
• Click on OK.
Program.cs
//Note: Create "C:\CSharp\sample.txt"
using System;
using System.IO;
namespace namespace1
{
class Program
{
static void Main()
{
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();
}
}
}
Output
o using System.IO;
o DirectoryInfo referencevariable;
• Create an object:
• Set properties:
o referencevariable.property = value ;
• Call method:
o referencevariable.methodname ();
Syntax: referencevariable.Parent.FullName
2 Name Represents only name of the folder (without parent folder’s path).
Syntax: referencevariable.Name
Syntax: referencevariable.FullName
4 Root.FullName Represents full path of the root folder of the current folder.
Syntax: referencevariable.Root.FullName
Syntax: referencevariable.Exists
Syntax: referencevariable.CreationTime
Syntax: referencevariable.LastAccessTime
Syntax: referencevariable.LastWriteTime
Syntax: referencevariable.Attributes
Syntax: referencevariable.Delete()
2 Delete(true) Deletes the current folder, including all of its files and sub
folders.
Syntax: referencevariable.Delete(true)
3 MoveTo() Movies the current folder into the specified destination path.
Syntax: referencevariable.MoveTo(string
DestinationFolderPath)
Syntax: referencevariable.CreateSubdirectory(string
newfoldername)
Syntax: referencevariable.GetFiles()
Syntax: referencevariable.GetDirectories()
Creating Project
• Create the following folders and files:
o C:\CSharp
▪ sample
• firstfolder (folder)
• secondfolder (folder)
• thirdfolder (folder)
• 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++)
{
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();
}
}
}
Output
• The “Directory” class is a static class, which provides a set of static methods to manipulate
folders.
o using System.IO;
o Directory.method ();
3 Delete() Deletes the specified folder permanently, including all of its sub folders
and files in it.
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
Creating Project
• Create the following folders:
o C:\CSharp
▪ Sample (folder)
• 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
Directory.CreateDirectory(@"C:\folder1");
Console.WriteLine("folder1 created");
Directory.Move(@"C:\folder1", @"C:\folder2");
Console.WriteLine("folder1 moved as folder2");
Console.ReadKey();
}
}
}
Output
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.
o using System.IO;
o File.method ();
2 Create() Create the specified file and returns corresponding FileStream’s object.
4 Move() Moves the specified source file into the specified destination location.
5 Copy() Copies the specified source file into the specified destination location.
Creating Project
• Create the following folders and files:
o C:\CSharp
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");
Output
• 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.
o “Create” mode: Used to create a new file and write data into the new file.
o using System.IO;
o FileStream referencevariable;
• Create an object:
o using System.IO;
o FileStream referencevariable;
• Create an object:
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.
o using System.IO;
o StreamWriter referencevariable;
• Create an object:
o referencevariable.Close ();
Creating Project
• Create the following folder:
o C:\CSharp
• 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();
Output
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.
o using System.IO;
o StreamReader referencevariable;
• Create an object:
o referencevariable.Close( );
Creating Project
• Create the following folder:
o C:\CSharp
• 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
Output
Database Basics
• DBMS (Database Management System): It is a software, which is used to store and
Table Structure
1 EmpID Int
2 EmpName Nvarchar(max)
3 Salary decimal
Table: Employees
1 Scott 5000
2 Allen 6000
3 Jones 7000
4 John 8000
5 Mark 9000
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.
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
15. System.Data.DataSet
16. System.Data.DataTable
17. System.Data.DataRow
18. System.Data.DataColumn
19. System.Data.DataView
System.Data.SqlClient.SqlConnection
• The “SqlConnection” is a class, which is a member of “System.Data.SqlClient” namespace.
Syntax: referencevariable.ConnectionString
= “connection string here”;
Syntax: referencevariable.State
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()
o using System.Data.SqlClient;
o SqlConnection referencevariable;
• Create an object:
o referencevariable.Open( );
o referencevariable.Close( );
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• This class’s object is used to execute an SQL statement or stored procedure through
database connection.
Syntax: referencevariable.Connection =
ReferenceVariableOfSqlConnectionClass;
Syntax: referencevariable.CommandType =
System.Data.CommandType.Optionhere;
Syntax:
referencevariable.Parameters.Add(ReferenceVari
ableOfSqlParameter)
Syntax: referencevariable.Transaction =
ReferenceVariableOfSqlTransaction;
Syntax: referencevariable.ExecuteScalar()
Syntax: referencevariable.ExecuteReader()
Syntax:
referencevariable.ExecuteNonQuery()
ADO.NET - ExecuteScalar
ExecuteScalar
• “ExecuteScalar” method is used to execute a “SELECT statement” or “stored procedure”
o using System.Data.SqlClient;
o SqlConnection cn;
o SqlCommand cmd;
• Create objects:
o cn = new SqlConnection();
• Call properties
o cmd.Connection = cn;
• Call methods
o cn.Open();
o cn.Close();
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
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();
cn.Close();
string n = Convert.ToString(obj);
string msg = "Emp Name: " + n;
Console.WriteLine(msg);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
cn.Close();
string n = Convert.ToString(obj);
Console.WriteLine("Emps Count: " + n);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• 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.
• 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.
2. System.Data.SqlClient.SqlCommand
3. System.Data.SqlClient.SqlDataReader
• 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.
1 [column index] object Retrieves the column value in the current record, based
on the column index.
2 [“column name”] object Retrieves the column value in the current record, based
on the column name.
Syntax: referencevariable.FieldCount
Syntax: referencevariable.HasRows
No constructors
Syntax: referencevariable.Read()
Syntax: referencevariable.GetValue(int
columnindex)
o using System.Data.SqlClient;
o SqlConnection cn;
o SqlCommand cmd;
o SqlDataReader dr;
• Create objects:
o cn = new SqlConnection();
• Call properties
o cmd.Connection = cn;
• Call methods
o cn.Open();
o dr = cmd.ExecuteReader( );
o dr.Read();
o dr[“column name”];
o cn.Close();
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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 */
/* 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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;
/* 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
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.
Syntax: referencevariable.ParameterName
= “parameter name here”
Syntax: referencevariable.Value
Syntax: referencevariable.DbType =
DbType.Optionhere;
Syntax: referencevariable.Direction =
ParameterDirection.Optionhere;
o using System.Data.SqlClient;
o SqlParameter p;
• Create object:
o p = new SqlParameter();
• Call properties
o cmd.Parameters.Add(p);
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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 objects */
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
/* 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);
Output
Note: If any database connection problem, it shows exception (run time error).
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.
• After loading all records at-once, the connection can be closed. That’s why it is called
“ADO.NET Disconnected Model”.
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.
DataSet - Example
Creating Project
• Open Visual Studio 2019.
• Click on OK.
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" };
ds.Tables.Add(dt1);
ds.Tables.Add(dt2);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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";
/* call methods */
adp.Fill(ds);
dt = ds.Tables[0];
for (int i = 0; i < dt.Rows.Count; i++)
{
drow = dt.Rows[i];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace MultipleTablesExample
{
class Program
{
static void Main()
{
/* 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];
obj3 = drow["Loc"];
int dno;
string dname;
string loc;
dno = Convert.ToInt32(obj1);
dname = Convert.ToString(obj2);
loc = Convert.ToString(obj3);
/* employees */
Console.WriteLine("\nEmployees:");
dt2 = ds.Tables[1];
n += 100;
for (int i = 0; i < dt2.Rows.Count; i++)
{
drow = dt2.Rows[i];
int eid;
string ename;
decimal sal;
int dno;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
dno = Convert.ToInt32(obj4);
Console.WriteLine(eid + ", " + ename + ", " + sal + ", " + dno);
}
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “departmentsandemployeesdatabase” database
already.
use departmentsandemployeesdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• Click on OK.
Program.cs
using System;
using System.Data.SqlClient;
using System.Data;
namespace JoinsExample
{
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=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];
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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
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;
//calling methods
cn.Open();
int n = cmd.ExecuteNonQuery();
cn.Close();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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 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 = "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();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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 objects
cn = new SqlConnection();
cmd = new SqlCommand();
p1 = new SqlParameter();
//calling properties
cn.ConnectionString = "data source=localhost; integrated
security=yes; initial catalog=company";
Output
Note: If any database connection problem, it shows exception (run time error).
• Stored procedures will be compiled once and executes every time when we call it. This is
called “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.
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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();
//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.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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: ");
//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();
Output
Note: If any database connection problem, it shows exception (run time error).
Creating Database
• Note: Ignore this step, if you have created “company” database already.
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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());
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();
Output
Note: If any database connection problem, it shows exception (run time error).
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.
▪ 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.
Creating Database
• Note: Ignore this step, if you have created “transactionsdatabase” database already.
use transactionsdatabase
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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;
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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• The System.Data.OleDb namespace is used to connect and interact with various databases
like Oracle, Excel, Access etc.
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
(or)
• Click on “Yes”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Next”.
• Click on “Install”.
• Click on “Finish”.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019.
• 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();
/* 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on OK.
• Click on “Create”.
• Click on OK.
• Click on “Yes”.
Creating Project
• Open Visual Studio 2019.
• 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();
/* 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Note: Ignore this step, if you have installed “Access Database Engine” already.
• Click on “Yes”.
• Click on “Next”.
• Click on “Install”.
• Click on OK.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• 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();
/* 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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019.
• 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;
/* 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];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
//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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• 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.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• 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;
/* 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];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
Console.ReadKey();
}
//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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
connect system/123;
commit;
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
• 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();
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();
}
cn = new SqlConnection();
cmd = new SqlCommand();
Output
Note: If any database connection problem, it shows exception (run time error).
use company
go
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
• 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.
• Click on “Save”.
Creating Project
• Open Visual Studio 2019.
• 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;
/* 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];
int eid;
string ename;
decimal sal;
eid = Convert.ToInt32(obj1);
ename = Convert.ToString(obj2);
sal = Convert.ToDecimal(obj3);
//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();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019. Go to “File” – “New” – “Project”.
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 objects
cn = new SqlConnection();
//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];
Console.ReadKey();
}
}
}
Output
Note: If any database connection problem, it shows exception (run time error).
• Click on “Execute” button. It shows “Query executed successfully” in the status bar.
Creating Project
• Open Visual Studio 2019.
• 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");