Download ADO.NET and Stored Procedures

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts

Microsoft SQL Server wikipedia , lookup

Microsoft Jet Database Engine wikipedia , lookup

Database wikipedia , lookup

Entity–attribute–value model wikipedia , lookup

Relational model wikipedia , lookup

Functional Database Model wikipedia , lookup

Clusterpoint wikipedia , lookup

Extensible Storage Engine wikipedia , lookup

Versant Object Database wikipedia , lookup

Database model wikipedia , lookup

Transcript

The first model used to access database, DAO (data access model)
was created for local databases.

Next RDO (Remote Data Object) & ADO (Active Data Object)
for Client Server architectures.

ADO was a good architecture but as the language changes so is the
technology.

ADO was a connected data access. Which raises concerns about
Database Security and network traffic.

ADO stands for “ActiveX Data Objects”.

ADO.NET is used to connect application system and database
server.

ADO.NET consists of a set of classes used to handle data access
and data services.

ADO.NET uses XML to store and transfer data among
applications, provide fast access of data for desktop and distributed
applications.

ADO.NET is scalable and interoperable.
ADO.net Objects are the means to access and modify the data in the Database.

Connects to databases.

Provider-specific classes
o SqlConnection
o OracleConnection
o OleDbConnection.

Connections can be opened in two ways:
o Explicitly by calling the “Open” method on the connection
o Implicitly when using a DataAdapter.

Connections handle transactions
SqlConnection conn = new SqlConnection
(“server=localhost; database=pubs; uid=mukka; pwd=“);
try{
conn.Open();
….}
catch (SqlConnection ex){ …..}
finally {
conn.Close();
}

Command objects are used to execute commands to a database
across a data connection.

These provide 3 methods to execute commands on database:
o ExecuteNonQuery: Executes commands that have no return values
such as INSERT, UPDATE or DELETE
o ExecuteScalar: Returns a single value from a database query
o ExecuteReader: Returns a result set by way of a DataReader object

Provider-specific classes
o SqlCommand
o OleDbCommand

Results are returned in the form of streams. Accessed by:
o DataReader object
o DataSet object via a DataAdapter.
ExecuteReader (for read)
ExecuteNonQuery (for updates)
SqlConnection conn = new SqlConnection (“server=localhost;
database=pubs; uid=mukka; pwd=“);
try {
conn.Open();
SqlCommand cmd = new SqlCommand ();
cmd.CommandText= “delete from title where title_id = “xxxx”;
cmd.Connection = conn;
cmd.ExecuteNonQuery ();
}
catch (SqlException ex) {
….}
finally { conn.Close();}

Provides methods and properties that deliver a forward-only
stream of data rows from a data source.

When a DataReader is used, parts of the ADO.NET model
are cut out, providing faster and more efficient data access.
try{ conn.Open();
SqlCommand cmd = new SqlCommand(“select * from titles”,
conn);
SqlDataReader reader = cmd.ExecuteReader();
While (reader.Read())
Console.WriteLine (reader[“title”]); }
******************
try {conn.Open(); SqlCommand cmd = new SqlCommand(“select *
from titles”, conn);
SqlDataReader reader = cmd.ExecuteReader();
for (int i=0; I <reader.FieldCount; i++) Console.WriteLine
(reader.GetName[i]));
}
reader.Close();

Provides a set of methods and properties to retrieve and save
data between a DataSet and its source data store.

Allows the use of stored procedures.

Connects to the database to fill the DataSet and also update
the database.

Types of DataAdapters
--SQLDataAdapter.
--ORACLEDataAdapter
--OleDbDataAdapter.
using System.Data;
using System.Data.SqlClient;
using System.Windows.Forms;
namespace WindowsFormsApplication9
{ public partial class Form1 : Form
{ public Form1()
{
InitializeComponent();
FillData();
}
void FillData()
{
using (SqlConnection c = new SqlConnection(
Properties.Settings.Default.DataConnectionString))
{
c.Open();
using (SqlDataAdapter a = new SqlDataAdapter("SELECT * FROM EmployeeIDs", c))
{
DataTable t = new DataTable();
a.Fill(t);
}
}
}
}
}

Replaces the ADO Recordset.

Represents a cache of data that contains tables, columns,
relationships, and constraints, just like a database.

Regardless of where the source data comes from, data can all
be placed into DataSet objects.

Tracks changes that are made to the data it holds before
updating the source data.

DataSet are also fully XML-featured.

Works with all current models of data storage: flat, relational,
and hierarchical
SqlDataAdapter ad = new SqlDataAdapter(“select * from
Categories",myConnection);
DataSet ds = new DataSet();
ad.Fill(ds,"Categories");
DataGrid1.DataSource = ds;
DataGrid1.DataBind();

Provides methods and properties that enable UI objects such
as a DataGrid to bind to a DataSet.

A view of the data contained in the DataSet.

Only used in conjunction with a DataSet
string connectionString = "..Nortwind Connection String.."; DataTable customers
= new DataTable("Customers");
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand selectAllCustomers = connection.CreateCommand();
selectAllCustomers.CommandText = "SELECT * FROM [Customers]";
connection.Open(); customers.Load(selectAllCustomers.ExecuteReader
(CommandBehavior.CloseConnection));
}
DataView dv = new DataView(customers,"Region = 'SP' and
Country = 'Brazil'", "ContactName",
DataViewRowState.CurrentRows);
dataGridView1.DataSource = dv;

It holds a table data from a data source; Data tables contains
two important properties:
1. COLUMNS
2. ROWS
-- DataRow Objects: Datarow objects correspond to a particular
row in a table. We use “Item” property to get or set a value in
a particular field in row.
-- DataColumn Objects: DataColumn objects represent the
columns in the table. Each DataColumn has a data type which
specify which type of data column contains.
DataSet dset;
DataTable dtbl;
DataRow drow;
drow=dtbl.NewRow();
drow["LastName"]="Altindag";
drow[1]="Altindag";
dtbl.Rows.Add(drow);
dtbl.Rows.Add(new object[] {1, "Altindag"});

Dataset support constraint objects to check data integrity
Constraints are of two types: Unique Constraint and foreign
constraint.
-- Unique Constraint check that new record entered is unique
throughout table
-- Foreign constraint specify that if one table is updated, how
the related records in another table would be affected.
--Not NULL constraint: it is used to check whether the column
with this constraint is filled or not.
using System;
using System.Data;
class Program
{
static void Main(string[] args)
{
DataTable dt1 = new DataTable("Table-1");
DataColumn pkCol = dt1.Columns.Add("Id", typeof(int));
dt1.Columns.Add("Field1", typeof(string)).MaxLength = 50;
dt1.PrimaryKey = new DataColumn[] { pkCol };
DataTable dt2 = new DataTable("Table-2");
dt2.Columns.Add("Id", typeof(int));
dt2.Columns.Add("Field1", typeof(string)).MaxLength = 50;
UniqueConstraint uc = new UniqueConstraint("PrimaryKey2", dt2.Columns["Id"], true);
dt2.Constraints.Add(uc);
DataTable dt3 = new DataTable("Table-3");
dt3.Columns.Add("Id1", typeof(int));
dt3.Columns.Add("Id2", typeof(int));
dt3.Columns.Add("Field1", typeof(string)).MaxLength = 50;
dt3.Constraints.Add("PrimaryKey3",new DataColumn[] { dt3.Columns["Id1"], dt3.Columns["Id2"] },true);
}
}

Data Relation objects specify a relationship between parent
and child tables, based on a key that both tables share.

You can then use the DataRelation object to get related
records.
private void Page_Load(object sender, System.EventArgs e)
{
DataSet ds = GetDataSet();
ds.EnforceConstraints = false;
DataRelation dl = new DataRelation("CHILDREN",
ds.Tables[0].Columns["id"], ds.Tables[1].Columns["parent"], false);
dl.Nested = true;
ds.Relations.Add(dl);
ComputeHierarchy(ds.Tables[0].Select("[parent] is null"), 0);
}
……........
…….........
……………

A stored procedure is a pre-defined, reusable routine that is stored
in a database.

SQL Server compiles stored procedures, which makes them more
efficient to use.

Therefore, rather than dynamically building queries in the code,
we can take advantage of the reuse and performance benefits of
stored procedures.

In addition to commands built with strings, the SqlCommand type
can be used to execute stored procedures.

There are two tasks require to make this happen:
1. let the SqlCommand object know which stored procedure to
execute.
// create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand( “xxxxx”, conn);
While declaring the SqlCommand object above, the first
parameter “xxxxx” is the name of a stored procedure in the
database. The second parameter is the connection object, which is
used for executing query strings.
2. tell the SqlCommand object that it is executing a stored
procedure.
set the command object so that it knows to execute a stored
procedure
cmd.CommandType = CommandType.StoredProcedure;
The second command tells the SqlCommand object what type of
command it will execute by setting its Command Type property to
the Stored Procedure.
Using parameters for stored procedures is the same as using
parameters for query string commands.
create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand( "CustOrderHist", conn);
2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
3. add parameter to command, which will be passed to the stored
procedure
cmd.Parameters.Add(new SqlParameter("@CustomerID", custId));
1.

The SqlCommand constructor above specifies the name of a
stored procedure.

This particular stored procedure takes a single parameter, named
“@CustomerID”. Therefore, we must populate this parameter
using a SqlParameter object.

The name of the parameter passed as the first parameter to the
SqlParameter constructor must be spelled exactly the same as the
stored procedure parameter. Then execute the command the
same as you would with any other SqlCommand object.

Initially create a object of SqlConnection class which is available in
System.Data.SqlClient namespace.

We have to provide the connection string as a parameter which
includes the Data Source name, the database name and the
authentication credentials.

Open the connection using the Open() method.

SqlConnection con = new SqlConnection("Data Source= ; initial
catalog= Northwind ; User Id= ; Password= '");
con.open();

Create the following stored procedure on the Region table in the
Northwind database which accepts two parameters and does not
have any output parameters.
CREATE PROCEDURE RegionUpdate (@RegionID INTEGER,
@RegionDescription NCHAR(50)) AS
SET
NOCOUNT OFF
UPDATE Region
SET RegionDescription = @RegionDescription

Create a SqlCommand object with the parameters as the name of
the stored procedure that is to be executed and the connection
object “con” to which the command is to be sent for execution.
SqlCommand command = new SqlCommand("RegionUpdate",con);

Change the command objects CommandType property to stored
procedure.
command.CommandType = CommandType.StoredProcedure;

Add the parameters to the command object using the Parameters
collection and the SqlParameter class.
command.Parameters.Add(new SqlParameter
("@RegionID",SqlDbType.Int,0,"RegionID"));
command.Parameters.Add(new SqlParameter
("@RegionDescription",SqlDbType.NChar,50,"RegionDescription"
));

Specify the values of the parameters using the Value property of
the parameters.
command.Parameters[0].Value=4;
command.Parameters[1].Value="SouthEast";

Excecute the stored procedure using the ExecuteNonQuery
method which returns the number of rows effected by the stored
procedure.
int i=command.ExecuteNonQuery();

Call the stored procedure and access the RegionDescription for
the RegionID 4 using the value property of the parameter.
string newRegionDescription =(string)
command.Parameters["@RegionDescription"].Value;

Close the sql connection.
con.Close();

http://www.startvbdotnet.com/ado/default.aspx

http://www.csharpstation.com/Tutorials/AdoDotNet/Lesson07.aspx.

http://www.codeproject.com/KB/cs/simplecodeasp.aspx.

http://www.developer.com/db/article.php/3438221/
Calling-Stored-Procedures-with-ADONET.htm