0% found this document useful (0 votes)
6 views79 pages

Unit5a Ref

The document discusses connecting to databases and accessing data using ADO.NET in C#. It covers topics like ADO.NET object model, disconnected vs connected data access, connecting to SQL Server and other databases, and using namespaces and classes for database access in C# applications.

Uploaded by

Niamrah Neha
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)
6 views79 pages

Unit5a Ref

The document discusses connecting to databases and accessing data using ADO.NET in C#. It covers topics like ADO.NET object model, disconnected vs connected data access, connecting to SQL Server and other databases, and using namespaces and classes for database access in C# applications.

Uploaded by

Niamrah Neha
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/ 79

Web Application using C#.

NET
Unit-5 – Part1
Database Access with Command,
Adapter and XML

11-5-2021,12-5-2021,13-5-2021, 14-5-2021, 17-5-2021,


18-5-2021

Dr.M.Paul Arokiadass Jerald


SYLLABUS
UNIT - V: DATABASE ACCESS WITH COMMAND,
ADAPTER AND XML
• ADO.NET Data Access - About the ADO.NET Example - Obtaining the
Sample Database - Simple Data Access - Simple Data Update - Importing
the Namespaces - Creating a Connection - The Connection String SQL -
Making the Connection - Defining the Select Command - Using a
Command with DataReader - Updating Data - Using Update - Insert - and
Delete Commands
• Accessing Disconnected Data - Selecting Disconnected Data - Selecting
Multiple Tables - Modifying Disconnected Data - Modifying and Deleting
Rows - Adding Information to a DataSet - Updating Disconnected Data -
The Command Builder - Updating a DataTable - Controlling Updates - An
Update Example
• Using XML - XML’s Hidden Role in .NET - XML Basics - Attributes -
Comments - The XML Classes - the XML TextWriter - The XML Text
Reader - Working with XML Documents - Reading an XML Document -
Searching an XML Document - XML
Web Application using C# - Unit 5
Validation – CreatingXML Schema
Dr.M.Paul Arokiadass Jerald 2

XSD Documents - Validating an XML File.
5.1 ADO.NET
• ADO.NET is a set of classes (a framework) to
interact with data sources such as databases
and XML files.
• ADO is the acronym for ActiveX Data
Objects.
• The data access classes for the .NET
framework
• Designed for highly efficient data access
• Support for XML and disconnected record
sets

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 3


ADO.Net in.NET framework
• A standard cross language interface
• Encapsulation of services, classes and data
types
• Uses XML for data representation

BENFITS OF ADO.NET
• Interoperability
• Scalability
• Productivity
• Performance

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 4


ADO.NET in .NET Framework

VB C# C++ Jscript …

Common Language Specification

Visual Studio .NET


ASP.NET Windows Forms

ADO.Net XML.Net

Base Class Library

Common Language Runtime (CLR)

Windows COM+ Services


Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 5
ADO
• ADO still exists.
• ADO is tightly coupled to client server
architectures
• Needs COM marshalling to pass data
between tiers
• Connections and locks are typically persisted

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 6


ADO Vs ADO.Net (Comparison)
Feature ADO ADO.Net
In memory Recordset object Dataset object
data storage Mimics single table Contains DataTables

Data Reads Sequential Sequential or non-


sequential

Data OLE/DB via the Managed provider


Sources Connection object calls the SQL APIs

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 7


ADO Vs ADO.Net (Comparison)
Feature ADO ADO.Net
Disconnected Limited support, Strong support,
data suitable for R/O with updating

Passing COM marshalling DataSet support for


datasets XML passing

Scalability Limited Disconnected access


provides scalability

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 8


The ADO.NET Object Model
DataTable DataSet
DataTable

SqlDataAdapter

OleDbDataAdapter

SQL Server .NET OLE DB .NET


Data Provider Data Provider
OleDbConnection
SqlConnection

SQL Server 7.0 OLEDB sources


(and later) (SQL Server 6.5) 9
5.2 .NET Data Providers
SQL .NET
SQL SERVER
Data Provider

OLE DB .NET OLE DB


Client Data Provider Provider Other DB

ODBC .NET ODBC


Data Provider Driver Other DB

10
Data Providers Functionality

Client .NET Data Provider

Connection Command
Rows
DataReader

DataSet
DataAdapter database

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass 11


Jerald
ADO.Net object model

Fill
DataAdapter DataSet
Update
UpdateCommand
Errors Collection
DeleteCommand
SelectCommand

InsertCommand

Command

Connection Parameters

Data Source

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 12


Disconnected Vs Connected
• In disconnected architecture a DataSet is used
for retrieving data from the database. Then no
need for maintaining the connection also. All the
operations can be performed with the data once
retrieved. It won't cause traffic problems while
working with the data.
• In connected architecture a DataReader is used
for retrieving data from the database. Here a
connection is always maintained. Update, Delete,
Read and Select operations can be performed as
the data is accessed in the database, so that a
connection must be be maintained.
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 13
Disconnected Vs Connected

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 14


5.3 Connecting to a Database
• Open Database Connectivity (ODBC): a standard
that allows ODBC-compliant applications to access
any data source for which there is an ODBC driver
• ODBC uses SQL commands to access a database
– ODBC then translates the SQL commands into a
format that the database understands
• .NET includes strong support for ODBC
• .NET also allows to work directly with SQL Server
and Oracle databases
– Working directly provides faster access

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 15


Access SQL Server Databases
• ActiveX Data Objects (ADO): a Microsoft
database connectivity technology that allows ASP
and other Web development tools to access
ODBC- and OLE-compliant databases
• OLE DB: a data source connectivity standard
promoted by Microsoft (Eg. Microsoft Access DB)
– Supports both relational and nonrelational data
sources
• ADO.NET: most recent version of ADO that allows
access to OLE DB-compliant data sources and
XML

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 16


MS-Access Databases

• Microsoft Data Access Components (MDAC):


components that make up Microsoft’s Universal
Data Access technology
– Include ADO and OLE DB
• MDAC is installed with many Microsoft products,
including Internet Explorer, Internet Information
Services, Visual Studio, and the .NET Framework
SDK

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 17


Namespaces in C#
• System.Data & System.Data.Common

• System.Data.SqlClient

• System.Data.OleDB

• System.Data.SqlTypes

• System.XML & System.XML.Schema

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 18


Using Namespaces in C#

• VB.Net
Imports System.Data
Imports System.Data.SqlClient
Dim sqlAdp as SqlDataAdapter
• C#
using System.Data;
using System.Data.SqlClient;
SqlDataAdapter sqlAdp= new
SqlDataAdapter();

• Use classes in the System.Data.SqlClient


namespace to access and manipulate SQL Server
databases
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 19
Understanding the
System.Data.SqlClient
Namespace (cont’d.)

Core ADO.NET objects

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 20


Connecting to an SQL Server
Database
• SqlConnection class: used to connect to an SQL
Server database
– Create an object from this class, passing in a
connection string
• Connection string must include the Data Source
parameter with the name of the SQL Server
instance you wish to use

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 21


Connecting to an SQL Server
Database (cont’d.)

SqlConnection class methods

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 22


Connecting to an SQL Server
Database (cont’d.)

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 23


SQL Namespace Objects

• using System.Data.SqlClient;
System.Data.SqlClient;
• SqlConnection
• SqlCommand
• SqlDataReader
• SqlDataAdapter
• SqlParameter
• SqlParameterCollection
• SqlError
• SqlErrorCollection
• SqlException
• SqlTransaction
• SqlDbType
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 24
Connecting to SQL

• using System.Data.SqlClient;

string sConnectionString =
"Initial Catalog=Northwind;
Data Source=localhost;
Integrated Security=SSPI;";

SqlDataAdapter sqlAdp= new


SqlDataAdapter(sConnectionString);

sqlAdp.Close();
sqlAdp.Dispose();
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 25
Connection Pooling

• ADO.Net pools connections.


When you close a connection it is released back into a pool.
• SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Integrated Security=SSPI;Initial Catalog=student";
conn.Open(); // Pool A is created.
• SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Integrated Security=SSPI;Initial Catalog=bsc";
conn.Open();
// Pool B is created because the connection strings differ.
• SqlConnection conn = new SqlConnection();
conn.ConnectionString =
"Integrated Security=SSPI;Initial Catalog=student";
conn.Open(); // The connection string matches pool A.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 26


Connecting to Database : Example
• MS-Access : Example
string conString
= "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=D:/essentials/jerald-
notes/c#/practical/ex9/crud/course.mdb;";
OleDbConnection con
= new OleDbConnection(conString);
con.Open();
• Refer Example (Exercise-7)
http://www.csresources.in/webapps/webapp_ex7.pdf

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 27


Opening and Closing a Data Source

• After creating a SqlConnection object, Open()


method is used to open the specified SQL Server
database instance
• Close() method disconnects the database connection
– Database connections do not automatically close when a
C# program ends
• Must verify that program has successfully connected to
a database before attempting to use it
• State property of the SqlConnection class: indicates
the current status of the database connection
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 28
Checking the Database Connection
(cont’d.)

SqlConnection class State property values

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 29


5.4 Using the command object
• SqlCommand
Multiple constructors

1.New()
2.New(cmdText)
3.New(cmdText, connection)
4.New(cmdText, connection,
transaction)
5.And many more

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 30


Using the command object
OleDbCommand cmd;
OleDbConnection conn = new
OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=|DataDirectory|\\course.mdb");
conn.Open();
OleDbDataAdapter adapter = new OleDbDataAdapter();
String insertsql = "insert into regn values ('" + name.Text + "','" +
rollno.Text + "','" + age.Text + "','" + courselist.Text + "','" +
durationlist.Text + "')";
cmd = new OleDbCommand(insertsql,conn);
adapter.InsertCommand = new OleDbCommand(insertsql,conn);
int m = adapter.InsertCommand.ExecuteNonQuery();
cmd.Dispose();
conn.Close();

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 31


Command Methods
• .ExecuteReader() - Returns DataReader
• .ExecuteNonQuery() - Returns # of Rows
Affected
• .ExecuteXMLReader() - Returns XMLReader
Object to Read XML documentation
• .ExecuteScaler() - Returns a Single Value e.g.
SQL SUM function.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 32


The DataReader object
• DataReader objects are highly optimised for
fast, forward only enumeration of data from
a data command
• A DataReader is available in connected
data access.
• Access to data is on a per record basis.
• Forward only
• Read only
• Does support multiple recordsets

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 33


5.5 Reading data
• SqlCommand
ExecuteReader()
ExecuteNonQuery()
ExecuteScalar()
ExecuteXMLReader()
• SqlDataAdapter
DataSet

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 34


Retrieving Records with the
SqlDataReader Class

• SqlCommand class: used to execute commands


against Microsoft SQL Server version 7.0 or later
• Syntax:
SqlCommand object = new SqlCommand
(“command”, connection)
– command parameter: contains the SQL command to
be executed
– connection parameter: represents the
SqlConnection object used to connect to the
database

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 35


Retrieving Records with the
SqlDataReader Class (cont’d.)

• DataReader object: used to retrieve read-only,


forward-only data from a data source
• Forward-only: the program can only move forward
sequentially through the records in the returned
data from the first to the last
• Use a DataReader object when you want to read
data but not add, delete, or modify records
• SqlDataReader class: used to retrieve data from
SQL Server

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 36


Retrieving Records with the
SqlDataReader Class (cont’d.)
• ExecuteReader() method of the SqlCommand
class: creates a SqlDataReader object
– Must assign the SqlDataReader object to a
variable
• Read() method of the SqlDataReader class:
advances the SqlDataReader object to the next
record
• Cursor: your position within the recordset
– Initially placed before the first row in the recordset
– First use of the Read() method places the cursor in
the first row of the recordset
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 37
Creating a data reader
Example :
SqlDataReader sqlReader;
sqlReader =
sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
// process, sqlReader("field")
}
sqlReader.Dispose();

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 38


Other Methods for Reading
• GetString(), GetInt() etc.
• GetSqlString(), GetSqlInt32() etc.
• GetValues()
• IsDBNull()
• GetSchemaTable()

Two Ways to get values


– .NET Managed types
– Strongly typed SQL data types

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 39


5.6 DataSets
• In-memory representation of data contained
in a database/XML
• Operations are performed on the DataSet,
not the data source
• Client Programs(C#) accesses the Dataset
• Can be created programmatically, using a
DataAdapter or XML schema and document
(or any mixture)
• Query from a table will create a dataset

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 40


Creating DataSets
1. Setup SqlConnection
2. Setup a SqlDataAdapter
3. Create a DataSet
4. Call the .Fill() method on the DataAdapter

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 41


5.7 DataAdapters
• Pipeline between DataSets and data sources
• Geared towards functionality rather than
speed
• Disconnected by design
• Supports select, insert, delete, update
commands and methods
• Must always specify a select command
• All other commands can be generated or
specified

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 42


Using the DataAdapter
string conString = "Provider=Microsoft.Jet.OLEDB.4.0;Data
Source=D:/ex10/crud/course.mdb;";
OleDbConnection con = new OleDbConnection(conString);
OleDbCommand cmd;
OleDbDataAdapter adapter;
DataTable dt = new DataTable();
con.Open();
adapter = new OleDbDataAdapter(cmd);
UpdateCommand = con.CreateCommand();
adapter.UpdateCommand.CommandText = sql;
if (adapter.UpdateCommand.ExecuteNonQuery() > 0)
{
clearTxts();
MessageBox.Show(@"Successfully Updated");
}
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 43
DataAdapters
• For speed and efficiency you should set your
own InsertCommand, UpdateCommand and
DeleteCommand
• Call GetChanges to seperates the updates,
adds and deletes since the last sync.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 44


DataTables

• A DataSet contains one or more DataTables.


• Fields are held within the DataTable.
• And in DataRows(Records),
DataColumns(Fields).

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 45


Sets, Tables and Rows

DataSet
DataTable
DataTable
DataRow
DataRow

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 46


Using DataTables
Operation that can be done in a DataTable
– Insert, modify and update
– Search
– Apply views
– Compare
– Clear
– Clone and Copy

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 47


DataRelations
• New to ADO.Net
• Tables within a DataSet can now have
relationships, with integrity.
• Supports cascading updates and deletes.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 48


DataViews
• Like a SQL view
• Single, or multiple tables
• Normally used with GUI applications via Data
Binding.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 49


Create Database

• Prerequisites: Microsoft SQL Server Management Studio


• Open Microsoft SQL Server Management Studio and
write the below script to create a database and table in it.
• create database Demodb;
• use Demodb;
• CREATE TABLE demo( articleID varchar(30) NOT NULL
PRIMARY KEY, articleName varchar(30) NOT NULL, );
• insert into demo values(1, 'C#');
• insert into demo values(2, 'C++');

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 50


Connecting with a Database

• Connecting C# with Database: The connection to a


database normally consists of the following parameters.
– Database name or Data Source: The database name to
which the connection needs to be set up and connection
can be made or you can say only work with one database
at a time.
– Credentials: The username and password which needs
to be used to establish a connection to the database.
– Optional Parameters: optional parameters provide more
information on how .NET should connect to the database
to handle the data.
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 51
Connection – Sample Code

// C# code to connect the database // The Initial Catalog is used to specify


using System; // the name of the database
using System.Data.SqlClient; // The UserID and Password are
credentials required to connect to
namespace Database_Operation {
database.
class DBConn {
constr = @"Data Source=DESKTOP-
// Main Method GP8F496;Initial Catalog=Demodb;User
static void Main() ID=sa;Password=abc123";
{ Connect();
Console.ReadKey(); conn = new SqlConnection(constr);
} // to open the connection
conn.Open();
static void Connect() Console.WriteLine("Connection Open!");
{ string constr; // to close the connection
// for the connection to sql server database conn.Close();
SqlConnection conn; }
// Data Source is the name of the server }
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass
} Jerald 52
Insert – Example Code
//to perform read and write operations
using System; SqlCommand cmd;
using System.Data.SqlClient;
namespace Database_Operation { // data adapter object is use to
class InsertStatement { // insert, update or delete commands
static void Main() SqlDataAdapter adap = new SqlDataAdapter();
{ Insert(); string sql = "";
Console.ReadKey();
} sql = "insert into demo values(3, 'Python')";
//execute the sql command
static void Insert() cmd = new SqlCommand(sql, conn);
{
string constr; // associate the insert SQL command to adapter
// connection to sql server database adap.InsertCommand = new SqlCommand(sql,
conn);
SqlConnection conn;
constr = @"Data Source=D:/ex1/GP8F496;
//execute the DML statement in database
Initial Catalog=Demodb;User ID=sa;Password=abc123";
adap.InsertCommand.ExecuteNonQuery();
conn = new SqlConnection(constr);
// closing all the objects
// to open the connection
cmd.Dispose();
conn.Open();
conn.Close();
} }}
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 53
Update – Code Example
sql = "update demo set articleName=chemical' where
articleID=3";
cmd = new SqlCommand(sql, conn);

// associate the update SQL command to adapter


adap.UpdateCommand = new SqlCommand(sql,
conn);

// use to execute the DML statement against


adap.InsertCommand.ExecuteNonQuery();

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 54


Delete – Code Example

SqlConnection conn; // define SQL statement


sql = "delete from demo where articleID=3";
constr = @"Data Source=D:/ex1/GP8F496;
Initial Catalog=Demodb;User // execute the sql command
ID=sa;Password=abc123"; cmd = new SqlCommand(sql, conn);
conn = new SqlConnection(constr);
// associate the insert SQL
// to open the connection // command to adapter
conn.Open(); adap.InsertCommand = new SqlCommand(sql, conn);
SqlCommand cmd;
//execute the DML statement
// data adapter object is use to adap.InsertCommand.ExecuteNonQuery();
// insert, update or delete commands
SqlDataAdapter adap = new SqlDataAdapter();
string sql = "";

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 55


Handling SQL Server Errors

• Must handle situations that occur when you cannot


connect to a database server
• Connection may fail because:
– The database server is not running
– You have insufficient privileges to access the data
source
– You entered an invalid username and password
• Other causes of errors:
– You are trying to open a nonexistent database
– You entered an invalid SQL statement

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 56


Using Exception Handling to Control
SQL Server Errors
• Place the Open() method within a try…catch
block to trap connection errors
• SqlException class:
– Part of the System.Data.SqlClient namespace
– Represents the exception that is thrown when SQL
Server returns an error or warning
– Number and Message properties provide an error
code and message for the exception

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 57


5.8 Executing SQL Commands

• System.Data.SqlClient namespace contains


classes to access and manipulate SQL Server
databases:
– SqlDataReader class
– SqlCommand class

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 58


Retrieving Records with the
SqlDataReader Class (cont’d.)

• Use the Read() method to determine if a next


record is available
– Returns true if there is another row in the recordset
• Field names in a database table are assigned as
variables in a SqlDataReader object collection
– Content of each variable changes when the cursor
position moves to a new row

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 59


Retrieving Records with the
SqlDataReader Class (cont’d.)

• Use the Close() method of the SqlDataReader


class to close it when you are finished working with
it
– SqlDataReader has exclusive access to the
connection object
– You cannot access any other commands until the
SqlDataReader object is closed

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 60


Executing SQL Commands with the
SqlCommand Object

• ExecuteNonQuery() method of the


SqlCommand object: executes commands against
a database
– Used for inserting, updating, or deleting rows in a
SQL Server database
– Does not return a recordset of data

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 61


CRUD USING C#
Creating and Deleting Databases
• Use the CREATE DATABASE statement with the
ExecuteNonQuery() method to create a new
database
– If database already exists, an error will occur
• Can test if the database exists with the
ChangeDatabase() method in a try…catch
block
– If unsuccessful, can create the database in the
catch block
• Use the DROP DATABASE statement with the
ExecuteNonQuery() method to delete a
database
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 63
Creating and Deleting Tables

• Use the CREATE TABLE statement with the


ExecuteNonQuery() method to create a new
table
• Must select the correct database with the
SqlConnection constructor or with the
ChangeDatabase() method before executing the
CREATE TABLE statement
• Can use the ExecuteReader() or
ExecuteNonQuery() methods to determine
whether the table already exists

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 64


Creating and Deleting Tables (cont’d.)

• IDENTITY keyword: used with a primary key to


generate a unique ID for each row in a new table
– First row’s identity value is 1
– Each subsequent row’s identity value increases by 1
• You can specify a start value and the increment
value if desired
• When adding records to a table with an IDENTITY
field, do not include a field value for the IDENTITY
field
• Use the DROP TABLE statement with the
ExecuteNonQuery() function to delete a table
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 65
Adding, Deleting,
and Updating Records

• Use the INSERT and VALUES keyword with the


ExecuteNonQuery() method to add a record
– Values in the VALUES list must be in the same order
in which the fields were defined in the table
– Specify NULL in any field for which you do not have
a value
• Use the BULK INSERT statement and the
ExecuteNonQuery() method to add multiple
records using data in a local text file

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 66


Adding, Deleting,
and Updating Records (cont’d.)
• Use the UPDATE, SET, and WHERE keywords with
the ExecuteNonQuery() method to update
records in a table
– UPDATE keyword specifies the table name
– SET keyword assigns values to fields
– WHERE keyword specifies which records to update
• Use the DELETE and WHERE keywords with the
ExecuteNonQuery() method to delete records in
a table
– To delete all records in a table, omit the WHERE
keyword

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 67


Disconnected Access

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 68


Disconnected Data Access
Architecture
• ADO.NET Framework supports two models of
Data Access Architecture,
– Connection Oriented Data Access Architecture and
– Disconnected Data Access Architecture.
• The ADO.NET Disconnected Data Access
Architecture far more flexible and powerful than
ADOs Connection Oriented Data Access.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 69


Disconnected Data Access
Architecture
• In Connection Oriented Data Access Architecture
the application makes a connection to the Data
Source and then interact with it through SQL
requests using the same connection.
• In this case the application stays connected to the
database system even when it is not using any
Database Operations.
• The disconnected approach makes no attempt to
maintain a connection to the data source.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 70


Disconnected Vs Connected
• In disconnected architecture a DataSet is used
for retrieving data from the database. Then no
need for maintaining the connection also. All the
operations can be performed with the data once
retrieved. It won't cause traffic problems while
working with the data.
• In connected architecture a DataReader is used
for retrieving data from the database. Here a
connection is always maintained. Update, Delete,
Read and Select operations can be performed as
the data is accessed in the database, so that a
connection must be be maintained.
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 71
Disconnected Data Access
Architecture
• ADO.Net provides a new solution by introduce a
new component called Dataset.
• The DataSet is the central component in the
ADO.NET Disconnected Data Access Architecture.
A DataSet is an in-memory data store that can hold
multiple tables at the same time.
• DataSets only hold data and do not interact with a
Data Source. One of the key characteristics of the
DataSet is that it has no knowledge of the
underlying Data Source that might have been used
to populate it.
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 72
Disconnected Data Access
Architecture
• VB.Net : Dim ds As New DataSet
• C# : DataSet ds = new DataSet();
• In Connection Oriented Data Access, when you
read data from a database by using a DataReader
object, an open connection must be maintained
between your application and the Data Source.
• Unlike the DataReader, the DataSet is not
connected directly to a Data Source through a
Connection object when you populate it.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 73


Disconnected Data Access
Architecture
• By keeping connections open for only a minimum
period of time, ADO.NET conserves system resources
and provides maximum security for databases and also
has less impact on system performance.

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 74


Summary
• Open Database Connectivity (ODBC) allows ODBC-
compliant applications to access any data source
• ODBC driver is required for data access
• ActiveX Data Objects (ADO) technology that allows
C# to access ODBC and OLE DB-compliant
databases
• System.Data.SqlClient namespace is used to
access and manipulate SQL Server databases
• SqlConnection class is used to connect to a SQL
Server database
• State property of the SqlConnection class is used
to determine the current status of the database
connection
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 75
Summary (cont’d.)
• Use the SqlException class to handle errors
• Use the SqlCommand class to execute commands against
SQL Server
• ExecuteReader() method with a DataReader object is
used to retrieve data from a SQL Server data source
• ExecuteNonQuery() method of the SqlCommand class
executes commands against a database
• CREATE DATABASE statement with
ExecuteNonQuery() method is used to create a new
database
• Use the CREATE TABLE statement with the
ExecuteNonQuery() method to create a new table
Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 76
Summary (cont’d.)
• Use the IDENTITY keyword with a primary key to
generate a unique ID for each new row in a table
• Use the DROP TABLE statement with the
ExecuteNonQuery() method to delete a table
• Use the INSERT and VALUES keywords with the
ExecuteNonQuery() method to add a new
record to a table
• Use the BULK INSERT statement with the
ExecuteNonQuery() method and a local text file
to add multiple new records to a table

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 77


Summary (cont’d.)
• Use the UPDATE, SET, and WHERE keywords with
the ExecuteNonQuery() method to update
records in a table
• Use the DELETE and WHERE keywords with the
ExecuteNonQuery() method to delete records in
a table

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 78


REFERENCES
• ADO.Net Programmer’s Reference
Bilbija, Dickenson et al. Wrox Press
• http://aspdotnet-
tutorial.blogspot.com/2011/01/building-data-
access-components-with.html
• http://msdn.microsoft.com
• For Exam purpose
https://www.c-
sharpcorner.com/UploadFile/d0a1c8/database-
programming-with-ado-net/

Web Application using C# - Unit 5 Dr.M.Paul Arokiadass Jerald 79

You might also like