0% found this document useful (0 votes)
4 views12 pages

Unit V Notes PDF

The document states that the training data is current only up to October 2023. No additional information or context is provided. It emphasizes the limitation of the data's recency.

Uploaded by

Viji
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)
4 views12 pages

Unit V Notes PDF

The document states that the training data is current only up to October 2023. No additional information or context is provided. It emphasizes the limitation of the data's recency.

Uploaded by

Viji
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/ 12

1

5.1 C# ADO.NET Connection String

Connection String is a normal String representation which contains Database connection


information to establish the connection between Database and the Application. The Connection
String includes parameters such as the name of the driver, Server name and Database name , as
well as security information such as user name and password.

Usually Data Providers use a connection string containing a collection of parameters to


establish the connection with the database through applications. The .NET Framework provides
mainly three data providers, they are:

 Microsoft SQL Server


 OLEDB
 ODBC

5.1.1 Making a connection string to the following ADO.NET Data Providers

Microsoft SQL Server Connection String


connetionString = "Data Source=ServerName;Initial Catalog=Databasename;
User ID=UserName;Password=Password"

OLEDB Data Provider Connection String


connetionString = "Provider=Microsoft.Jet.OLEDB.4.0;
Data Source=yourdatabasename.mdb;"

ODBC Connection String

connetionString="Driver={Microsoft Access Driver (*.mdb)};


DBQ=yourdatabasename.mdb;"

5.1.2 Fundamentals of Database connectivity

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#.

5.1.3 connecting C# to Database

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-2: Click on Windows Forms Application(.NET Framework) in the middle of current


window. After that give the project name (WindowsFormsApplication1 is the default
name) and Click OK. Solution name is same as the project name.

Step-3: Go to Tools Menu and choose Connect to Database


4

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.

OleDbConnection con = new OleDbConnection();


con.ConnectionString="Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS; Integrated Security=SSPI;Initial
Catalog=master";
con.Open();

5.1.4 C# SQL Server Connection


C# application is connected to data in a SQL Server database using the .NET Framework
Data Provider for SQL Server. The first step in a C# application is to create an instance of the
Server object and to establish its connection to an instance of Microsoft SQL Server. The
SqlConnection Object is Handling the part of physical communication between the C#
application and the SQL Server Database . An instance of the SqlConnection class in C# is
supported the Data Provider for SQL Server Database. The SqlConnection instance takes
Connection String as argument and pass the value to the Constructor statement.

Sql Server connection string:

connetionString="Data Source=ServerName; Initial Catalog=DatabaseName;


User ID=UserName; Password=Password"
5

If there is a named instance of SQL Server, it is need to add that as follows;

"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.

A Sample C# Program that connect SQL Server using connection string.

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

catch (Exception ex)


{
MessageBox.Show("Can not open connection ! ");
}
}
}
}

5.2 Creating a Command Object in c#


Command in C# allow the user to query and send the commands to the database.
command is specified by the OleDb connection object. Two methods are used, ExecuteReader
method for results of query and ExecuteNonQuery for insert, Update, and delete commands. It is
the method that is best for the different commands.
Syntax for creating command object
OleDbCommand cmdObject = new OleDbCommand(String SQL, OleDbConnection con);
Example of creating command object
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
con.Open();
String SQL ="insert into Product values(" + Convert.ToInt32(textBox1.Text) + ",'" +
textBox2.Text + "'," + Convert.ToDouble(textBox3.Text) + ")";
OleDbCommand cmd = new OleDbCommand(SQL,con);
The SQL language includes several nonquery commands. The best known include
UPDATE, DELETE, and INSERT. You can also use other commands to create, alter, or drop
tables, constraints, relations, and so on. To execute any of these commands, just set the
CommandText property with the full SQL statement, open a connection, and invoke the
ExecuteNonQuery( ) method. The next sections consider examples that update, delete, and insert
records.

5.2.1 Updating a record

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

OleDbCommand cmd = new OleDbCommand(SQL,con);


cmd.ExecuteNonQuery();

5.2.2 Deleting a record

Syntax :

DELETE FROM table 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 = "DELETE FROM Categories WHERE CategoryID=1";
OleDbCommand cmd = new OleDbCommand(SQL,con);
cmd.ExecuteNonQuery();

5.2.3 Inserting a record

Syntax :

INSERT INTO table (column_list) VALUES (value_list)


Example:
OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply-
PC\\SQLEXPRESS;Integrated Security=SSPI;Initial Catalog=master";
con.Open();
string SQL = "INSERT INTO Categories (CategoryName, Description) " +
"VALUES ('Beverages', 'Soft drinks, coffees, teas, beers, and ales')";
OleDbCommand cmd = new OleDbCommand(SQL,con);
cmd.ExecuteNonQuery();

5.2.4 Selecting records from tables

Syntax :

SELECT aggregate_expression FROM tables [WHERE search_condition]

[ORDER BY order_expression ASC | DESC];


8

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

5.3 DataSet and DataAdapter

ADO.NET has a Connection object to manage database connection to required data


source. Like ADO, ADO.NET also has a Command object. The Command object is used to
submit SQL statements or to execute stored procedures. Like the ADO Command object, the
ADO.NET Command object accepts parameters and supports re-executing compiled commands.
ADO.NET DataSet object used for holding tables, relations, and columns.
The ADO Recordset object held a collection of records that we could scroll through. The
ADO.NET DataSet can do the same but can hold several sets of records and the relationships
between them. The ADO.NET DataSet is like a portable database containing tables and views
along with the data description information that defines them. We can consider an ADO.NET
DataSet to be an in-memory database that we hold in our application's memory space (see the
sidebar, "The DataReader," for the one exception to ADO.NET's separation of client and server).

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".

public abstract int Fill


(
DataSet dataSet;
)
The Fill method retrieves rows from the data source using the SELECT statement
specified by an associated SelectCommand property. The Fill operation then adds the rows to
destination DataTable objects in the DataSet, creating the DataTable objects if they do not
already exist. When creating DataTable objects, the Fill operation normally creates only column
name metadata. However, if the MissingSchemaAction property is set to AddWithKey,
appropriate primary keys, and constraints are also created.
10

Populating a DataSet using DataAdapter

The ADO.NET DataSet is a memory-resident representation of data that provides a


consistent relational programming model independent of the data source. The DataSet represents
a complete set of data including tables, constraints, and relationships among the tables. Because
the DataSet is independent of the data source, a DataSet can include data local to the application,
as well as data from multiple data sources. Interaction with existing data sources is controlled
through the DataAdapter.

The SelectCommand property of the DataAdapter is a Command object that retrieves


data from the data source. The InsertCommand, UpdateCommand, and DeleteCommand
properties of the DataAdapter are Command objects that manage updates to the data in the data
source according to modifications made to the data in the DataSet. The Fill method of the
DataAdapter is used to populate a DataSet with the results of the SelectCommand of the
DataAdapter. Fill takes as its arguments a DataSet to be populated, and a DataTable object, or
the name of the DataTable to be filled with the rows returned from the SelectCommand.

Example

OleDbConnection con = new OleDbConnection();


con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply- PC\\SQLEXPRESS;
Integrated Security=SSPI;Initial Catalog=master";
con.Open();
DataSet ds = new DataSet();
OleDbDataAdapter ad = new OleDbDataAdapter("select * from item", con);
ad.Fill(ds);
dataGridView1.DataSource = ds.Tables[0].DefaultView;
11

5.4 Data Reader

 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

// Create a connection string


OleDbConnection con = new OleDbConnection();
con.ConnectionString = "Provider=SQLOLEDB;Data Source=Simply- PC\\SQLEXPRESS;
Integrated Security=SSPI;Initial Catalog=master";
con.Open();
// Create a command object
OleDbCommand cmd = new OleDblCommand(SQL, conn);
conn.Open();

// Call ExecuteReader to return a DataReader


OleDbDataReader reader = cmd.ExecuteReader();
Console.WriteLine("customer ID, Contact Name, " + "Contact Title, Address ");
Console.WriteLine("==========================================");

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();

You might also like