Module 7
Module 7
Database
Connectivity
Click on Browse and type “[Link]” and press enter.
Database
Connectivity
Click on install
Database
Connectivity
Click on ok
Database
Connectivity
Click on “I Accept”
Database
Connectivity
On Installation it will show as shown here:
Database
Connectivity
Now we have the namespace “[Link]” added to our
application
Connectivity
Database
Connectivity Right click on Data Connections
Select Create new SQL Server Database
Database
Connectivity
Put server name as “(localdb)\MSSQLLOCALDB”
Click on ok
Database
Connectivity
A database will be created
Database
Connectivity
If you have database, already created, for e.g we want to connect again
to Emp database, which we have created above.
Database
Connectivity
Right click on Data Connections
Click on Add Connections
Database
Connectivity
Click on Continue
Database
Connectivity
Put server name as
(localdb)\MSSQLLOCALDB
Select Emp
Connectivity
Click on ok
[Link] is a set of classes that expose data access services for .NET
Framework programmers.
[Link]
Architecture The two main components of [Link] for accessing and manipulating
data are the .NET Framework data providers and the DataSet.
The .NET Framework Data Providers are components that have been
explicitly designed for data manipulation and fast, forward-only, read-only
access to data.
The Connection object provides connectivity to a data source.
The Command object enables access to database commands to return data,
.NET modify data, run stored procedures, and send or retrieve parameter
Framework
information.
The DataReader provides a high-performance stream of data from the data
Data source.
Providers Finally, the DataAdapter provides the bridge between the DataSet object
and the data source.
The DataAdapter uses Command objects to execute SQL commands at the
data source to both load the DataSet with data and reconcile changes that
were made to the data in the DataSet back to the data source.
A .NET Framework data provider is used for connecting to a database,
executing commands, and retrieving results.
Those results are either processed directly, placed in a DataSet in order to
be exposed to the user as needed, combined with data from multiple
sources, or remoted between tiers. .
.NET NET Framework data providers are lightweight, creating a minimal layer
Framework
between the data source and code, increasing performance without
sacrificing functionality.
Data
Providers
.NET Framework data provider - Description.
NET Framework Data Provider for SQL - ServerProvides data access for
Microsoft SQL Server. Uses the [Link] namespace.
.NET .NET Framework Data Provider for OLE DB - For data sources exposed by
using OLE DB. Uses the [Link] namespace.
Framework
Data .NET Framework Data Provider for ODBC - For data sources exposed by
Providers using ODBC. Uses the [Link] namespace.
.NET Framework Data Provider for Oracle - For Oracle data sources. The
.NET Framework Data Provider for Oracle supports Oracle client software
version 8.1.7 and later, and uses the [Link] namespace
The 4 core objects that make up a .NET Framework data provider.
1. Connection - Establishes a connection to a specific data source. The base
class for all Connection objects is the DbConnection class.
2. Command - Executes a command against a data source.
Core Objects Exposes Parameters and can execute in the scope of a Transaction from
a Connection. The base class for all Command objects is
of .NET the DbCommand class.
Framework 3. DataReader - Reads a forward-only, read-only stream of data from a data
source. The base class for all DataReader objects is
Data the DbDataReader class.
Providers 4. DataAdapter - Populates a DataSet and resolves updates with the data
source. The base class for all DataAdapter objects is
the DbDataAdapter class.
The [Link] DataSet is explicitly designed for data access independent
of any data source.
As a result, it can be used with multiple and differing data sources, used
with XML data, or used to manage data local to the application.
DataTable objects consisting of rows and columns of data, and also primary
key, foreign key, constraint, and relation information about the data in
the DataTable object.
The following diagram illustrates the relationship between a .NET
Framework data provider and a DataSet.
DataSet
The SQL Server managed provider comes with a similar set of objects,
whose names start with SqlClient instead of OleDb
The implementation of this core function set for managed providers is
packaged in the [Link] namespace, while the interfaces for
the data adapter classes are in [Link].
Sql 4. ConnectionString - Gets or sets the string used to open a SQL Server
database.
Connection
Methods:
1. ChangeDatabase() - Changes the current database for an
open SqlConnection.
2. Open()- Opens a database connection with the property settings specified
by the ConnectionString.
3. Close() - Closes the connection to the database. This is the preferred
method of closing any open connection.
Command 3. ExecuteScalar() - Executes the query, and returns the first column of the
first row in the result set returned by the query. Additional columns or
rows are ignored.
Properties:
1. Connection - Gets or sets the SqlConnection used by this instance of
the SqlCommand.
2. CommandTimeout - Gets or sets the wait time (in seconds) before
terminating the attempt to execute a command and generating an error.
3. CommandType - Gets or sets a value indicating how the CommandText
property is to be interpreted. The default is Text.
Sql 4. CommandText - Gets or sets the Transact-SQL statement, table name or
Command stored procedure to execute at the data source. The default is empty string.
Provides a way of reading a forward-only stream of rows from a SQL
Server database.
On running the ExecuteReader() method of SqlCommand Object, a
instance of DataReader is returned.
We can refer that returned instance with reference of SqlDataReader.
Lets look the example reads through the data, writing it out to the console
window.
Sql
DataReader
using System;
using [Link];
using [Link];
class Program {
static void Main() {
string str = "Data Source=(localdb)\MSSQLLOCALDB;Initial Catalog=Emp;"
Sql + "Integrated Security=true";
DataReader ReadOrderData(str);
}
private static void ReadOrderData(string cs) {
string query= @"SELECT empid,empname FROM empData;";
using (SqlConnection connection = new SqlConnection(cs))
{ SqlCommand command = new SqlCommand(query, connection);
[Link]();
SqlDataReader reader = [Link]();
Sql // Call Read before accessing data.
DataReader while ([Link]()) {
[Link](reader[0]+” “+ reader[1]);
}
[Link](); // Call Close when done reading.
} }}
Properties:
1. Connection - Gets the SqlConnection associated with the SqlDataReader.
2. FieldCount - Gets the number of columns in the current row.
3. HasRows - Gets a value that indicates whether the SqlDataReader
contains one or more rows.
4. IsClosed - Retrieves a Boolean value that indicates whether the
Sql specified SqlDataReader instance has been closed.
DataReader
Methods:
1. GetByte() - Gets the value of the specified column as a byte.
2. GetChar() - Gets the value of the specified column as a single character.
3. GetDouble Gets the value of the specified column as a double-precision
floating point number.
4. GetFloat() - Gets the value of the specified column as a single-precision
Sql 5.
floating point number.
GetValue() - Gets the value of the specified column in its native format.
DataReader
Represents a set of data commands and a database connection that are used
to fill the DataSet and update a SQL Server database.
This class cannot be inherited.
The SqlDataAdapter, serves as a bridge between a DataSet and SQL Server
for retrieving and saving data.
The SqlDataAdapter provides this bridge by mapping :
Sql 1. Fill, which changes the data in the DataSet to match the data in the data
source, and
DataAdapter 2. Update, which changes the data in the data source to match the data in
the DataSet, using the appropriate Transact-SQL statements against the
data source. The update is performed on a by-row basis.
Lets initializes a new instance of the SqlDataAdapter class.
Constructor’s:
1. SqlDataAdapter() - Initializes a new instance of
the SqlDataAdapter class.
2. SqlDataAdapter(SqlCommand) - Initializes a new instance of
the SqlDataAdapter class with the specified SqlCommand as
the SelectCommand property.
Sql 3. SqlDataAdapter(String, SqlConnection) - Initializes a new instance of
DataAdapter the SqlDataAdapter class with a SelectCommand and
a SqlConnection object.
4. SqlDataAdapter(String, String) - Initializes a new instance of
the SqlDataAdapter class with a SelectCommand and a connection
string.
Example:
string cs=@”Data Source = (localdb)\MSSQLLOCALDB; Initial Catalog =
Emp; Integrated Security = true”;
string query = @”select empid,empname from empData;”;
using (SqlConnection connection = new SqlConnection(cs))
{
Sql [Link]();
DataTable DataRelation
Collection Collection
DataRow Data
Collection ColumnCollection
DataRow DataColumn
Represents one table of in-memory data.
Following example creates an instance of a DataTable object and assigns it
the name “Emp“
DataTable workTable = new DataTable(“Emp");
A DataTable contains a collection of DataColumn objects referenced by
the Columns property of the table.
This collection of columns, along with any constraints, defines the schema, or
structure, of the table.
You create DataColumn objects within a table by using the DataColumn
constructor, or by calling the Add method of the Columns property of the
table, which is a DataColumnCollection.
The Add method accepts optional ColumnName, DataType, and Expression
DataTable arguments and creates a new DataColumn as a member of the collection.
It also accepts an existing DataColumn object and adds it to the collection,
and returns a reference to the added DataColumn if requested.
Because DataTable objects are not specific to any data source, .NET
Framework types are used when specifying the data type of a DataColumn.
Example: Adding 3 Columns to DataTable
DataTable workTable = new DataTable(“Emp");
DataColumn workCol = [Link](“EmpID", typeof(Int32));
[Link] = false;
[Link] = true;
[Link](“EmpName", typeof(String));
DataTable
Example
DataTable
Example
Add Checkbox to previous Form, which enable, to visit and display the
records of DataTable.
Activity
Add the following code to existing code, to display records using Previous
and Next button in [Link] file.
Activity
To display Previous and Next, on the state of checkbox, add the following
code to existing code, in [Link] file.
Activity
Till now we have created DataTable Manually by extracting data from
compnents of form.
Lets add the data to the DataTable from the Data Source.
working with
data source
Given form to be Loaded.
working with
data source
As soon as you click Load, the data from employee table shown before, will
be added consisting of columns emp_id, name, sal only.
working with
data source
working with
data source
working with
data source
Now if you have more than one table to be loaded , you create Dataset and
load it from DataSource.
Lets say we have products table as shown below:
working with
data source
And we have Emp table as shown before
working with
data source
Now lets load a Form with data from both the tables using data set.
working with
data source
Now lets load a Form with data from both the tables using data set.
working with
data source
working with
data source
working with
data source
[Link] supports two different programming environments: connected and
disconnected.
Connected
and
[Link]
disconnected
architecture
Connected Disconnected
The connected environment provides forward-only, read-only access to data
in the data source and the ability to execute commands against the data
source.
The connected classes provide a common way to work with connected data
regardless of the underlying data source.
Disconnected Figure in next slide shows the relationship between the connected and
disconnected classes in [Link].
Relationship
Between
Connected &
Disconnected
Architecture
Disconnected ➢Corresponds to a row in a table and can examine and update data in the DataTable.
➢ The DataTable exposes DataRow objects through the DataRowCollection object
Classes it contains.
➢The DataRow caches changes made to data contained in its columns, storing both
original and current values.
➢This allows changes to be cancelled or to be later reconciled with the data source.
Constraint:
➢Allows constraints to be placed on data stored within a DataTable.
➢Unique and foreign key constraints can be created to maintain data integrity.
DataRelation:
➢Provides a way to indicate a relationship between different DataTable objects
within a DataSet.
➢The DataRelation relates columns in the parent and child tables allowing
navigation between the parent and child tables and referential integrity to be
enforced through cascading updates and deletes.
DataView:
Disconnected ➢Allows data, once retrieved into a DataSet or DataTable, to be viewed in
Classes different ways.
➢It allows data to be sorted based on column values and for a subset of the data
to be filtered so that only rows matching specified criteria are displayed.
Difference between Connected and Disconnected Architecture
Connected Disconnected
Connected you need to use a read only In Disconnected you cannot use.
forward only data reader
Data Reader can’t persist the data DataSet can persist the data
You can use the DataGridView control to show read-only views of a small
amount of data, or you can scale it to show editable views of very large sets of
data
.
DataGridView With the DataGridView control, you can display and edit tabular data from
many different kinds of data sources
.
Binding data to the DataGridView control is straightforward and intuitive, and
in many cases it is as simple as setting the DataSource property.
When you bind to a data source that contains multiple lists or tables, set
the DataMember property to a string that specifies the list or table to bind to.
The DataGridView control is highly configurable and extensible, and it
provides many properties, methods, and events to customize its appearance
and behavior.
When you want your Windows Forms application to display tabular data,
consider using the DataGridView control before others (for
example, DataGrid).
DataGridView If you are displaying a small grid of read-only values, or if you are enabling a
user to edit a table with millions of records, the DataGridView control will
provide you with a readily programmable, memory-efficient solution.
In a toolbox search box type DataGridView to locate component in toolbox
DataGridView
DataGridview displays tabular data, you can specify the table format
manually by adding columns or you can assign DataSource from where this
component will be loaded with tabular information.
Specifying the table information to be displayed Manually
Click on Add Columns
DataGridView
It will display the window as shown below:
DataGridView
Lets add 2 columns RollNo and Name
Adding Coloumn 1-Roll No, provide details of columns and click on Add.
DataGridView
Similarly Add Coloumn 2-First Name, provide details of columns and click
on Add, then click on Close.
DataGridView
Similarly Add Coloumn 2-First Name, provide details of columns and click
on Add, then click on Close.
After applying above steps the datagridview looks as shown below
DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button
DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button
DataGridView
Now lets add, 2 TextBox for taking roll number and name as input, and
adding the information in DataGridView on clicking Add button
DataGridView
DataGridView
DataGridView
DataGridView
Specifying the DataSource for DataGridview to display the tabular data
directly without adding columns.
The DataSource is DataTable, however you can set DataSource to Dataset but
in that case you need to set the DisplayMember.
Lets go Through Example.
A Form is there with DataGridView as shown below:
DataGridView
To load this DataGridView with information from data source, using DataSet
DataGridView
DataGridView
DataGridView data source is DataTable, to the previous form we add button
named “Load DataTable”, on clicking it will add the content of DataTable for
display in DataGridView.
DataGridView
Add the following code in the existing code shown for form9 before
DataGridView