Unit V Notes PDF
Unit V Notes PDF
C# and .Net can work with a majority of databases, the most common being Oracle and
Microsoft SQL Server. But with every database, the logic behind working with all of them is
mostly the same. In working with databases, the following are the concepts which are common
to all databases.
Connection – To work with the data in a database, the first obvious step is the
connection. The connection to a database normally consists of the below-mentioned parameters.
Database name or Data Source – The first important parameter is the database name to
which the connection needs to be established. Each connection can only work with one database
at a time.
2
Credentials – The next important aspect is the username and password which needs to be
used to establish a connection to the database. It ensures that the username and password have
the necessary privileges to connect to the database.
Optional parameters – For each database type, you can specify optional parameters to
provide more information on how .net should handle the connection to the database. For
example, one can specify a parameter for how long the connection should stay active. If no
operation is performed for a specific period of time, then the parameter would determine if the
connection has to be closed.
Selecting data from the database – Once the connection has been established, the next
important aspect is to fetch the data from the database. C# can execute „SQL‟ select command
against the database. The „SQL‟ statement can be used to fetch data from a specific table in the
database.
Inserting data into the database – C# can also be used to insert records into the
database. Values can be specified in C# for each row that needs to be inserted into the database.
Updating data into the database – C# can also be used to update existing records into
the database. New values can be specified in C# for each row that needs to be updated into the
database.
Deleting data from a database – C# can also be used to delete records into the database.
Select commands to specify which rows need to be deleted can be specified in C#.
we will connect to The database is connected to C# application using database name and
credentials. Let, Username – Simply-PC\SQLEXPRESS
The following steps describe to develop a simple Windows forms application to work
with databases.
Step-1: Open Visual Studio and choose File->New->Project to create a new project and then
select the language as Visual C# from the left menu.
3
Step-4: Type the Server name “Simply-PC\SQLEXPRESS” (Server name is system name in
case of local server and SQLEXPRESS), select the database “master” and press the test
button. If the test connection is succeeded, then press ok to connect with the database.
Step-5: Now double click the form so that an event handler is added to the code for the button
click event. In the event handler, add the below code.
"Server=localhost\sqlexpress"
When the connection is established , SQL Commands will execute with the help of the
Connection Object and retrieve or manipulate the data in the database. Once the Database
activities is over , Connection should be closed and release the Data Source resources.
cnn.Close();
The Close() method in SqlConnection Class is used to close the Database Connection. The Close
method rolls back any pending transactions and releases the Connection from the SQL Server
Database.
using System;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string connetionString = null;
SqlConnection cnn ;
connetionString="Data Source=ServerName;Initial Catalog=DatabaseName;User
ID=UserName;Password=Password"
cnn = new SqlConnection(connetionString);
try
{
cnn.Open();
MessageBox.Show ("Connection Open ! ");
cnn.Close();
}
6
Syntax :
UPDATE table SET update_expression WHERE search_condition
Example:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
con.Open();
string SQL = "UPDATE Categories SET CategoryName='Beverages'" +
"WHERE CategoryID=1";
7
Syntax :
Example:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
con.Open();
string SQL = "DELETE FROM Categories WHERE CategoryID=1";
OleDbCommand cmd = new OleDbCommand(SQL,con);
cmd.ExecuteNonQuery();
Syntax :
Syntax :
Example:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
con.Open();
string SQL = "SELECT count(empid) FROM employee; "
OleDbCommand cmd = new OleDbCommand(SQL,con);
int result = (int)cmd.ExecuteScalar();
con.Close();
9
DataAdapter
The completely new object in the ADO.NET world is the DataAdapter. The purpose of
the DataAdapter is embedded in its name: It performs the activities necessary to get the data
from the data source on the server into the database that's held in the DataSet. To do that, the
DataAdapter lets us specify the commands that should be carried out to retrieve and update data.
The DataAdapter improves on this process. The object provides four properties that allow us to
control how updates are made to the server: SelectCommand, UpdateCommand,
InsertCommand, and DeleteCommand. The four properties are set to Command objects that are
used when data is manipulated.
For instance, when we call the DataAdapter's Fill method to retrieve data from a data source and
pour it into a DataSet, the Command object in the SelectCommand property is used. The
DataAdapter is the gatekeeper that sits between our DataSet and the data source. Instead of using
Command objects directly with a Connection, the DataAdapter manages our Command objects
as they interact with the data source.
DataAdapter.Fill Method
Adds or refreshes rows in the DataSet to match those in the data source using the DataSet name,
and creates a DataTable named "Table".
Example
There are two common objects in ADO.NET to read data, DataSet and
DataReader.
C# DataSet and C# DataReader classes represent these objects.
A data reader provides an easy way for the programmer to read data from a database as if
it were coming from a stream. The DataReader is the solution for forward streaming data through
ADO.NET. The data reader is also called a firehose cursor or forward read-only cursor because it
moves forward through the data. The data reader not only allows you to move forward through
each record of database, but it also enables you to parse the data from each column. The
DataReader class represents a data reader in ADO.NET.
Similar to other ADO.NET objects, each data provider has a data reader class for
example; OleDbDataReader is the data reader class for OleDb data providers. Similarly,
SqlDataReader and ODBC DataReader are data reader classes for SQL and ODBC data
providers, respectively.
The IDataReader interface defines the functionally of a data reader and works as the base
class for all data provider-specific data reader classes such as OleDataReader. SqlDataReader,
and OdbcDataReader. Figure 5-36 shows some of the classes that implement IDbDataReader.
12
Example
while (reader.Read())
{
Console.Write(reader["CustomerID"].ToString() + ", ");
Console.Write(reader["ContactName"].ToString() + ", ");
Console.Write(reader["ContactTitle"].ToString() + ", ");
Console.WriteLine(reader["Address"].ToString() + ", ");
}
//Release resources
reader.Close();
conn.Close();