0% found this document useful (0 votes)
27 views59 pages

3 WorkingWithData

The document discusses ADO.NET and its object model for working with data in .NET applications. It describes ADO.NET as a technology for communicating with databases and its core namespaces like System.Data. It explains the main objects in ADO.NET - data objects like DataSet that store local copies of data, and connection objects like SqlConnection and SqlCommand that are used to connect to and execute commands on a data source. It provides an overview of tasks like establishing a database connection, executing queries using a DataReader or Command, and updating/inserting data.

Uploaded by

akshay patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
27 views59 pages

3 WorkingWithData

The document discusses ADO.NET and its object model for working with data in .NET applications. It describes ADO.NET as a technology for communicating with databases and its core namespaces like System.Data. It explains the main objects in ADO.NET - data objects like DataSet that store local copies of data, and connection objects like SqlConnection and SqlCommand that are used to connect to and execute commands on a data source. It provides an overview of tasks like establishing a database connection, executing queries using a DataReader or Command, and updating/inserting data.

Uploaded by

akshay patel
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 59

DOT NET TECHNOLOGY

Working with Data

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology
Active Data Object - ADO.NET
• ADO.NET allows us to interact with relational
databases and other data source.

• Technology to communicate with a database.

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 2
ADO.NET Object Model
• Data Namespaces
▫ System.Data
 Contains fundamental classes with core ADO.NET
functionality
 DataSet, DataRelation

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 3
ADO.NET Object Model
• Data Namespaces
▫ System.Data.OleDb
 Contains classes to connect to OLE DB provider
 Classes: OleDbCommand, OleDbConnection

▫ System.Data.SqlClient
 Contains classes to connect to Microsoft SQL Server
database
 Classes: SqlDbCommand, SqlDbConnection

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 4
ADO.NET Object Model
• Data Namespaces
▫ System.Data.SqlTypes
 Contains structures for SQL Server-specific data types
 Structures: SqlMoney, SqlDateTime

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 5
ADO.NET Object Model
• ADO.NET Objects:

• Two groups of objects:


▫ Objects that are used to contain and manage data
 DataSet, DataTable, DataRow, DataRelation

▫ Objects that are used to connect to a data source


 Connections, Commands, DataReader

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 6
ADO.NET Object Model
• The Data Objects
• Allows to store a local, disconnected copy of data
▫ DataSet Object
▫ DataTable Object
▫ DataRow Object
▫ DataColumn Object
▫ DataRelation Object
▫ DataView Object

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 7
Data source interaction objects
• SqlConnection & OleDbConnection
▫ Establish a connection
▫ First step in any database operation

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 8
Data source interaction objects
• SqlCommand & OleDbCommand
▫ Represent an SQL statement or stored procedure to retrieve,
update or modify data
▫ To use command, use DataAdapter or one of the methods
below:

▫ ExecuteNonQuery: Executes command without retrieving


any information. Ideal for Insert, Update or Delete operations

▫ ExecuteReader: Creates DataReader object that allows to


retrieve rows from the data source. Ideal for Select operation

▫ ExecuteScalar: Creates Reader that returns a single value


instead of rows; first column from the first row of resulting
rowset
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 9
Data source interaction objects
• SqlDataReader & OleDbReader
▫ Provide a steady stream of data
▫ Fastest way to read data when we want to display
data on the web page
▫ Used with Select operation
▫ Don’t allow any changes or updates
▫ Method: Read

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 10
Data source interaction objects
• SqlDataAdapter & OleDbAdapter
▫ Bridge between a Command and a DataSet

SQL
Command DataAdapter DataSet
Statement

▫ We can create an SQL statement to select a set of rows,


create a Command that represents it and use
DataAdapter to automatically retrieve all matching rows
and insert them into a supplied DataSet

▫ Reference to 4 commands
 DeleteCommand
 InsertCommand
 SelectCommand
 UpdateCommand
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 11
Data source interaction objects
• SqlDataAdapter & OleDbAdapter
▫ Methods:
 Fill: executes SelectCommand and places the results
into the DataSet we supply

 Update: searches through the supplied DataSet and


applies all the changes it finds to the data source.
InsertCommand, UpdateCommand or
DeleteCommand is required

 FillSchema: uses the SelectCommnad to retrieve


information about a table and add it to a DataSet

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 12
ADO.NET Data Access
• Simple Data Access
1. Create Connection, Command and DataReader
objects
2. Use DataReader to retrieve information from
database
3. Display results in a control on a web form
4. Close Connection
5. Send page to the user

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 13
ADO.NET Data Access
• Simple Data Updates
1. Create Connection and Command objects
2. Execute the command with appropriate SQL
statement
3. Use ExecuteNonQuery method to execute the SQL
statement

• Importing NameSpaces
▫ using System.Data
▫ using System.Data.OleDb / System.Data.SqlClient

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 14
Creating a Connection
• Specify value of a ConnectionString property

• ConnectionString defines all the information the computer


needs to find the data source, login and choose an initial
database

• Syntax:
SqlConnection MyConn = new SqlConnection();
MyConn.ConnectionString = “Provider = SQLOLEDB; Data Source =
localhost; Initial Catalog = TestDatabase; User ID=sa";

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 21
ConnectionString
• Provider
▫ Name of OLEDB provider
▫ SQLOLEDB for SQL
• Data Source
▫ Name of the server where the data source is located
▫ ‘localhost’ if server is on same machine
• Initial catalog
▫ Name of the database that this connection will be
accessing
• User ID & Password
▫ ID and password to access the database

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 22
Connection String
Creating a Connection
SqlConnection MyConn = new SqlConnection();
MyConn.ConnectionString = @"Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\MyWebApp1\App_Data\T
estDatabase.mdf;Integrated Security=True;User Instance=True";

• Making a Connection:
MyConnection.Open();

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 25
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection MyConn = new SqlConnection();

MyConn.ConnectionString = @"Data
Source=.\SQLEXPRESS;AttachDbFilename=D:\MyWebApp1\App_Da
ta\Test Database.mdf;Integrated Security=True;User Instance=True";

MyConn.Open();

Label1.Text = "<b> Server Version:</b>";


Label1.Text += MyConn.ServerVersion;
Label1.Text += "<b> Connection is:</b>";
Label1.Text += MyConn.State.ToString();

MyConn.Close();
}
Part 1: Establish a Connection:
i. Create a Connection object
ii. Write a Connection String
iii. Open the connection

Part 2: Execute SQL statement:


i. Create a Command object
ii. Connect the Command object with Connection object
iii. Create and execute SQL query using CommandText method

Part 3: DateReader for SELECT operation:


i. Create a DataReader object
ii. Execute the DataReader object with ExecuteReader() method
iii. Use Read() method to retrieve matching rows
OR
Part 3: For UPDATE/DELETE/INSERT operation:
i. Use ExecuteNonQuery method on command object to perform
update/delete /insert operation
Part 1: Establish a Connection: SqlConnection MyConn = new SqlConnection();
i. Create a Connection object
ii. Write a Connection String MyConn.ConnectionString = @“<Connection String>";

iii. Open the connection


MyConn.Open();

Part 2: Execute SQL statement:


i. Create a Command object
ii. Connect the Command object with Connection object
iii. Create and execute SQL query using CommandText method

Part 3: DateReader for SELECT operation:


i. Create a DataReader object
ii. Execute the DataReader object with ExecuteReader() method
iii. Use Read() method to retrieve matching rows
OR
Part 3: For UPDATE/DELETE/INSERT operation:
i. Use ExecuteNonQuery method on command object to perform
update/delete /insert operation
Part 1: Establish a Connection:
i. Create a Connection object
SqlCommand cmd = new SqlCommand();
ii. Write a Connection String
iii. Open the connection
cmd.Connection = MyConn;

Part 2: Execute SQL statement:


cmd.CommandText = “<SQL Query>";
i. Create a Command object
ii. Connect the Command object with Connection object
iii. Create and execute SQL query using CommandText method

Part 3: DateReader for SELECT operation:


i. Create a DataReader object
ii. Execute the DataReader object with ExecuteReader() method
iii. Use Read() method to retrieve matching rows
OR
Part 3: For UPDATE/DELETE/INSERT operation:
i. Use ExecuteNonQuery method on command object to perform
update/delete /insert operation
Part 1: Establish a Connection:
i. Create a Connection object
ii. Write a Connection String
iii. Open the connection SqlDataReader MyReader;

Part 2: Execute SQL statement: MyReader = cmd.ExecuteReader();


i. Create a Command object
ii. Connect the Command object with Connection object
iii. Create and execute SQL query using CommandText method

Part 3: DateReader for SELECT operation: MyReader.Read();


MyReader[“<Field_Name>"].ToString()
i. Create a DataReader object
ii. Execute the DataReader object with ExecuteReader() method
iii. Use Read() method to retrieve matching rows
OR
Part 3: For UPDATE/DELETE/INSERT operation:
i. Use ExecuteNonQuery method on command object to perform
update/delete /insert operation
Part 1: Establish a Connection:
i. Create a Connection object
SqlCommand cmd = new SqlCommand();
ii. Write a Connection String
iii. Open the connection
cmd.Connection = MyConn;

Part 2: Execute SQL statement:


cmd.CommandText = “<SQL Query>";
i. Create a Command object
ii. Connect the Command object with Connection object
iii. Create and execute SQL query using CommandText method

Part 3: DateReader for SELECT operation:


i. Create a DataReader object
ii. Execute the DataReader object with ExecuteReader() method
iii. Use Read() method to retrieve matching rows
OR cmd.ExecuteNonQuery();
Part 3: For UPDATE/DELETE/INSERT operation:
i. Use ExecuteNonQuery method on command object to perform
update/delete /insert operation
Defining a Select Command
• Define an SQL statement to select information
• Take a Command object that executes the SQL
statement
• Take a DataReader or DataSet to catch the
retrieved records
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = “SELECT * from Table_Name";

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 33
DataReader
• Quickly retrieve all your results
• Use ExecuteReader method to create a DataReader
SqlDataReader MyReader;
MyReader = cmd.ExecuteReader();

• Retrieve a row using a Read command


MyReader.Read();

• Access values of the retrieved row


ListBox1.Items.Add(MyReader["ID"].ToString() + " , " +
MyReader["PWD"].ToString());

• Use Read() method again to retrieve next row or use


while(MyReader.Read())
{
ListBox1.Items.Add(MyReader["ID"].ToString() + " , " +
MyReader["PWD"].ToString());
}
Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 34
Closing the connection

MyReader.Close();

MyConnection.Close();

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 36
Updating Data
• Insert, Update & Delete commands

• Create a command object

• Execute the command with ExecuteNonQuery


method

• This method returns the number of rows that


were affected

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 37
Updating a Record
• Create a command object

• Execute the command with ExecuteNonQuery method

• This method returns the number of rows that were


updated

• Write SQL query for UPDATE

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 38
Reading a Record
• Before updating any record, retrieve it from the
data source using DataReader

• Ex: Table Test1(ID, PWD)


• List IDs in a DropdownList
• Display that record in Textboxes

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 40
using System.Data.SqlClient;

public partial class SQLUpdateData : System.Web.UI.Page


{
SqlConnection MyConn = new SqlConnection(@"Data
Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=c:\users\hp\documents\visual studio
2015\Projects\Local_DB_Test_App\Local_DB_Test_App\App_Data\MyDB_1.mdf;Integrated
Security=True");

protected void Page_Load(object sender, EventArgs e)


{
// continue…
if (!IsPostBack)
{
MyConn.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = MyConn;
cmd.CommandText = "select ID from Test1";

// Define a DataReader
SqlDataReader MyReader;
MyReader = cmd.ExecuteReader();

// retrieve a row
while (MyReader.Read())
{
DropDownList1.Items.Add(MyReader["ID"].ToString());
}
MyReader.Close();
MyConn.Close();
}
}
protected void DropDownList1_SelectedIndexChanged(object sender, EventArgs e)
{ // Make AutoPostBack property of DropDownList to True

MyConn.Open();
String SelectSQL;
SelectSQL = "Select * from Test1 where ID = '" +
DropDownList1.SelectedItem.Value + "'";

SqlCommand cmd = new SqlCommand();


cmd.Connection = MyConn;
cmd.CommandText = SelectSQL;

// Define a DataReader
SqlDataReader MyReader;
MyReader = cmd.ExecuteReader();

// continue
// retrieve a row
while (MyReader.Read())
{

TextBox1.Text = MyReader["ID"].ToString();
TextBox2.Text = MyReader["PWD"].ToString();
}
MyReader.Close();

}
protected void UpdateButton_Click(object sender, EventArgs e)
{
String UpdateSQL;

UpdateSQL = "UPDATE Test1 set ID = '"+ TextBox1.Text +"', PWD = '" +


TextBox2.Text + "' where ID = '"+ DropDownList1.SelectedItem.Value +"'" ;

MyConn.Open();

SqlCommand cmd = new SqlCommand();


cmd.Connection = MyConn;
cmd.CommandText = UpdateSQL;

int updated;
updated = cmd.ExecuteNonQuery();

Label1.Text = updated.ToString() + " record(s) updated";


}
Record Updated
Deleting a Record
• Create a command object

• Execute the command with ExecuteNonQuery method

• Write SQL query for DELETE

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 51
protected void DeleteButton_Click(object sender, EventArgs e)
{
String DeleteSQL;

DeleteSQL = “DELETE from Test1 where ID = '" + DropDownList1.SelectedItem.


Value + "'";
MyConn.Open();

SqlCommand cmd = new SqlCommand();


cmd.Connection = MyConn;
cmd.CommandText = DeleteSQL;

int deleted;
deleted = cmd.ExecuteNonQuery();

Label1.Text = deleted.ToString() + " record(s) deleted";

}
Adding a Record
• Create a command object

• Execute the command with ExecuteNonQuery method

• Write SQL query for INSERT

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology 55
protected void CreateNewButton_Click(object sender, EventArgs e)
{
TextBox1.Text = "";
TextBox2.Text = "";
}
protected void InsertNewButton_Click(object sender, EventArgs e)
{
String InsertSQL;
InsertSQL = “INSERT into Test1 (ID, PWD) values ('"+TextBox1.Text+"',
'"+TextBox2.Text+"')";
MyConn.Open();

SqlCommand cmd = new SqlCommand();


cmd.Connection = MyConn;
cmd.CommandText = InsertSQL;

int added;
added = cmd.ExecuteNonQuery();

Label1.Text = added.ToString() + " record(s) added";


}
Record Added
End

Prof. Bhumika Patel Sarvajanik College of Eng. & Tech., Surat Dotnet Technology

You might also like