Programming in C#
Programming in C#
Programming in C#
Unit-5
Database Programming with C#
11-1-2021,18-1-2021,20-1-2021,
21-1-2021,22-1-2021,23-1-2021,25-1-2021
UNIT - V: DATABASE
• Creating Connection String – Creating a
Connection to a Database
• Creating a Command Object
• Working with Data Adapters
• Using Data Reader to work with Databases
• Using Dataset.
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
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
ADO.NET in .NET Framework
ADO.Net XML.Net
OLE DB .NET
Client Data Provider
OLE DB
Other DB
Provider
Connection Command
Rows
DataReader
DataSet
DataAdapter database
ADO.Net object model
Fill
DataAdapter DataSet
Update
UpdateCommand
Errors Collection
DeleteCommand
SelectCommand
InsertCommand
Command
Connection Parameters
Data Source
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
12
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
• System.Data.SqlClient
• System.Data.OleDB
• System.Data.SqlTypes
• 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();
17
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
Programming with C# 20
SQL Namespace Objects
• using System.Data.SqlClient;
System.Data.SqlClient;
• SqlConnection
• SqlCommand
• SqlDataReader
• SqlDataAdapter
• SqlParameter
• SqlParameterCollection
• SqlError
• SqlErrorCollection
• SqlException
• SqlTransaction
• SqlDbType
Connecting to SQL
• using System.Data.SqlClient;
string sConnectionString =
"Initial Catalog=Northwind;
Data Source=localhost;
Integrated Security=SSPI;";
sqlAdp.Close();
sqlAdp.Dispose();
Connection Pooling
26
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
Using the command object
• string sSelectQuery =
"SELECT * FROM Categories ORDER BY CategoryID";
string sConnectionString =
"Initial Catalog=Northwind;
Data Source=localhost;
Integrated Security=SSPI;";
SqlConnection objConnect = new SqlConnection(sConnectString);
SqlCommand objCommand = new SqlCommand(sSelectQuery,
objConnect);
/*
• objCommand.CommandTimeout = 15;
objCommand.CommandType = CommandType.Text;
• */
objConnect.Open();
SqlDataReader drResults;
drResults;
drResults = objCommand.ExecuteReader()
objCommand.ExecuteReader()
drResults.Close();
objConnect.Dispose();
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.
The DataReader object
• DataReader objects are highly optimised for
fast, forward only enumeration of data from
a data command
• A DataReader is not disconnected
• Access to data is on a per record basis.
• Forward only
• Read only
• Does support multiple recordsets
5.5 Reading data
• SqlCommand
ExecuteReader
ExecuteNonQuery
ExecuteScalar
ExecuteXMLReader
• SqlDataAdapter
DataSet
Retrieving Records with the
SqlDataReader Class
32
Retrieving Records with the
SqlDataReader Class (cont’d.)
33
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
34
Creating a data reader
SqlDataReader sqlReader;
sqlReader =
sqlCommand.ExecuteReader();
while (sqlReader.Read())
{
// process, sqlReader("field")
}
sqlReader.Dispose();
Other Methods for Reading
• GetString(), GetInt() etc.
• GetSqlString(), GetSqlInt32() etc.
• GetValues()
• IsDBNull()
• GetSchemaTable()
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
Creating DataSets
• Setup SqlConnection
• Setup a SqlDataAdapter
• Create a DataSet
• Call the .Fill() method on the DataAdapter
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
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(); Refer (Click)
con.Open(); Exercise 10
adapter = new OleDbDataAdapter(cmd);
UpdateCommand = con.CreateCommand();
adapter.UpdateCommand.CommandText = sql;
if (adapter.UpdateCommand.ExecuteNonQuery() > 0)
{
clearTxts();
MessageBox.Show(@"Successfully Updated");
}
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.
DataTables
DataSet
DataTable
DataTable
DataRow
DataRow
Using DataTables
With a DataTable we can
• Insert, modify and update
• Search
• Apply views
• Compare
• Clear
• Clone and Copy
DataRelations
• New to ADO.Net
• Tables within a DataSet can now have
relationships, with integrity.
• Supports cascading updates and deletes.
DataViews
• Like a SQL view
• Single, or multiple tables
• Normally used with GUI applications via Data
Binding.
Create Database
53
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
54
5.8 Executing SQL Commands
55
Retrieving Records with the
SqlDataReader Class (cont’d.)
56
Retrieving Records with the
SqlDataReader Class (cont’d.)
57
Executing SQL Commands with the
SqlCommand Object
58
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
60
Creating and Deleting Tables
61
Creating and Deleting Tables (cont’d.)
63
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
64
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 65
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
66
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
67
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
68
REFERENCES
• ADO.Net Programmer’s Reference
Bilbija, Dickenson et al. Wrox Press
• http://msdn.microsoft.com
• http://www.csharphelp.com/
• http://www.csharp-station.com/
• http://www.csharpindex.com/
• http://www.c-sharpcorner.com/
• https://www.w3schools.com/cs/
• https://www.javatpoint.com/c-sharp-tutorial
• https://www.bestprog.net/en/site-map/c/