Top Banner

of 28

Ado.net 2.0 Day1

Apr 07, 2018

Download

Documents

Vani Chopra
Welcome message from author
This document is posted to help you gain knowledge. Please leave a comment to let me know what you think about it! Share it to your friends and learn new things together.
Transcript
  • 8/6/2019 Ado.net 2.0 Day1

    1/28

    ADO.Net 2.0

    Aids in database connectivity

  • 8/6/2019 Ado.net 2.0 Day1

    2/28

    What Is Database Connectivity

    Data used by the applications is stored in a database.

    This database is external to the application

    It is retrieved into the application as required by the

    program. This retrieval is achieved by writing the code that

    provides a link between the application & database.

    This link is known as database connectivity.

    This link is used to send the commands to the database

    & getting the corresponding results.

  • 8/6/2019 Ado.net 2.0 Day1

    3/28

    Role of Microsoft.Net

    It has provided classes that aid in the databaseconnectivity.

    All these classes are located in the System.Datanamespace.

    These classes perform the following tasks

    Communication with the database

    Storing the data in the database

    Fetching the data in the database

    Updating the data in the database These classes makes the core data access objects in

    .NET Framework

    These are collectively known as ADO.NET

  • 8/6/2019 Ado.net 2.0 Day1

    4/28

    Required NameSpaces

    ADO.NET ships with four database clientnamespaces

    System.Data.SqlClient

    System.Data.Oledb System.Data.Odbc

    System.Data.OracleClient

  • 8/6/2019 Ado.net 2.0 Day1

    5/28

    ADO.NET contains a number of classes thatare used irrespective of the namespace youare using to fetch data

    DataSet

    DataTable

    DataRow

    DataColumn

    DataRelation

    DataColumnMapping

    DataTableMapping

    Shared Classes

    System.Data

    System.Data.Common

  • 8/6/2019 Ado.net 2.0 Day1

    6/28

    Database specific Classes The following classes can be prefixed each with Oledb,

    SQL, Oracle, ODBC for respective database Command : wrappers for SQL statements or stored

    procedure calls.

    CommandBuilder: Used to generate SQL commands Connection: Used to connect to the database

    DataAdapter: Used to hold select, insert, update, anddelete commands, which are then used to populate aDataSet and update the Database

    DataReader: Used as a forward only, connected datareader

    Parameter: Used to define a parameter to a storedprocedure.

    Connection: Used for a database transaction, wrapped inan object.

  • 8/6/2019 Ado.net 2.0 Day1

    7/28

    Database specific Classes The most important feature of the ADO.NET classes is

    that they are designed to work in a disconnectedmanner, which is important in today's highly Web-centricworld.

    ADO 2.1 introduced the disconnected record set, whichwould permit data to be retrieved from a database,passed to the client for processing, and then reattachedto the server.

    This used to be cumbersome to use, becausedisconnected behavior was not part of the originaldesign.

    The ADO.NET classes are different in all but one case(the DataReader) they are designed for useoffline from the database.

  • 8/6/2019 Ado.net 2.0 Day1

    8/28

    Connection A representation of an open connection to the database

    It does not perform the following tasks

    Doesnt fetch or update data

    Doesnt execute queries A Connection object is

    A pipeline that commands & queries use to send data& retrieve results

    It is a place to set the connection string

  • 8/6/2019 Ado.net 2.0 Day1

    9/28

    Connection

    ConnectionObject

    Command&

    Queries

    Information from

    the data source &Returned data

    Database

  • 8/6/2019 Ado.net 2.0 Day1

    10/28

    Connection in Server Explorer Visual Studio provides server explorer as the window to

    create connection

    This connection can be used in any project

  • 8/6/2019 Ado.net 2.0 Day1

    11/28

    Connections throug

    hData

    Wizards

    Data Source configuration wizard is used for building thedatabase connection

    Using this wizard, you need to select the database path& you end up with a configured connection object readyto use in your application.

    Apart from that, the wizard also allows you to select thedatabase objects you want to use in your application

    You can also bind your controls with different columns inthe database. Binding is of two types

    Simple Binding : 1 Conrtol is bound to 1 column

    Complex Binding : 1 Control is bound to many columns

  • 8/6/2019 Ado.net 2.0 Day1

    12/28

    Different ways of fetching data

    DataReader

    Stores a single row at a time in the

    memory Requires a constant connection with the

    database

    DataSet

    Stores one or more tables Is a disconnected, cached set of records

    that are retrieved from the database

  • 8/6/2019 Ado.net 2.0 Day1

    13/28

    Connection Objects throug

    hCode

    You can also create connection at runtime by writing thecode to create Connection Object

    First of all, you need to select the type of connection youwant.

    This choice depends on the database you are connectingcommunicating with

    Name Target Data Source

    SQL Connection SQL Server Database (2000 onwards)Oledb Connection OLEDB data Source such as Access

    ODBC Connection Use DSN

    Oracle Connection Oracle databases

  • 8/6/2019 Ado.net 2.0 Day1

    14/28

    Connection Object Each Connection Object contains the same base

    properties, methods & events that are inherited from theSystem.Data.Common.DbConnection class

    Properties

  • 8/6/2019 Ado.net 2.0 Day1

    15/28

    Connection PropertiesName Description

    ConnectionString Gets or Set the String to open the connection

    ConnectionTimeout Gets the time to wait while establishing the

    connection before generating an errorDatabase Gets the name of current database after connection

    is open or the database name specified in theconnection string before the connection is opened

    DataSource Gets the name of database server to which it isconnected

    ServerVersion Gets a string that represents the version of theserver to which the object is connected

    State Gets a string that describes the state of theconnection

  • 8/6/2019 Ado.net 2.0 Day1

    16/28

    SQL Server 2005 Connection The code to connect to SQL Server is:

    private SqlConnection sql = new SqlConnection (@"DataSource=user\sqlexpress;InitialCatalog=AdventureWorks;Integrated Security=True");

    Or

    private SqlConnection sql = new SqlConnection();

    sql.ConnectionString = @"DataSource=user\sqlexpress;InitialCatalog=AdventureWorks;Integrated Security=True";

  • 8/6/2019 Ado.net 2.0 Day1

    17/28

    Commands A command is, in its simplest form, a string of text

    containing SQL statements that is to be issued to thedatabase.

    A command could also be a stored procedure, or thename of a table that will return all columns and all rowsfrom that table

  • 8/6/2019 Ado.net 2.0 Day1

    18/28

    Using Commandstring source = @"Data Source=user\sqlexpress;Initial

    Catalog=AdventureWorks;Integrated Security=True";

    string select = "SELECT ContactName,CompanyNameFROM Customers";

    SqlConnection conn = new SqlConnection(source);

    conn.Open();

    SqlCommand cmd = new SqlCommand(select, conn);

  • 8/6/2019 Ado.net 2.0 Day1

    19/28

    CommandType Command classes have a property called

    CommandType, which is used to define the type of command

    CommandType Example

    Text (default) String select = "SELECT ContactName FROMCustomers"; SqlCommand cmd = newSqlCommand(select , conn);

    StoredProcedure SqlCommand cmd = newSqlCommand("CustOrderHist", conn);cmd.CommandType =

    CommandType.StoredProcedure;cmd.Parameters.AddWithValue("@CustomerID", "QUICK");

    TableDirect OleDbCommand cmd = newOleDbCommand("Categories", conn);cmd.CommandType =

    CommandType.TableDirect;

  • 8/6/2019 Ado.net 2.0 Day1

    20/28

    Executing Commands ExecuteNonQuery() Executes the command but does

    not return any output

    ExecuteReader() Executes the command and returnsa typed IDataReader

    ExecuteScalar() Executes the command and returns asingle value

    In addition to these methods, the SqlCommand classexposes the following method:

    ExecuteXmlReader() Executes the command andreturns an XmlReader object, which can be used totraverse the XML fragment returned from the database.

  • 8/6/2019 Ado.net 2.0 Day1

    21/28

    ExecteNonQuery Used for UPDATE, INSERT, or DELETE statements, where

    the only returned value is the number of recordsaffected.

    This method can, however, return results if you call astored procedure that has output parameters

    string select = "string select = "UPDATE Customers " + "SETContactName = 'Bob' " + "WHERE ContactName = 'Bill'";

    SqlCommand cmd = new SqlCommand(select, conn);

    int rowsReturned = cmd.ExecuteNonQuery();

    Console.WriteLine("{0} rows returned.", rowsReturned);

  • 8/6/2019 Ado.net 2.0 Day1

    22/28

    ExecuteR

    eader This method executes the command and returns a typed

    data reader object, depending on the provider in use.

    The object returned can be used to iterate through the

    record(s) returned

    string select = "SELECT ContactName,CompanyNameFROM Customers";

    SqlDataReader reader = cmd.ExecuteReader();while(reader.Read())

    {

    Console.WriteLine("Contact : {0,-20} Company : {1}" ,reader[0] , reader[1]);

    }

  • 8/6/2019 Ado.net 2.0 Day1

    23/28

    ExecuteScalar Used to return a single result from a SQL statement,

    such as the count of records in a given table

    string select = "SELECT COUNT(*) FROM Customers"; SqlCommand cmd = new SqlCommand(select, conn); object o

    = cmd.ExecuteScalar();

    Console.WriteLine ( o ) ;

  • 8/6/2019 Ado.net 2.0 Day1

    24/28

    Calling Stored Procedures Calling a stored procedure with a command object is

    a matter of defining the name of the stored procedure,

    adding a definition for each parameter of the procedure,

    then executing the command with one of the methods

  • 8/6/2019 Ado.net 2.0 Day1

    25/28

    Stored Procedure The following stored procedure can be created in SQL

    Server 2005

    This procedure updates the data in the table

    CREATE PROCEDURE RegionUpdate (@RegionID

    INTEGER, @RegionDescription NCHAR(50))AS

    SET NOCOUNT OFF UPDATE Region

    SET RegionDescription = @RegionDescriptionWHERERegionID = @RegionID

    GO

  • 8/6/2019 Ado.net 2.0 Day1

    26/28

    Calling the stored procedure from

    .Net CodeSqlCommand aCommand = newSqlCommand("RegionUpdate", conn);

    aCommand.CommandType =CommandType.StoredProcedure;

    aCommand.Parameters.Add(new SqlParameter("@RegionID", SqlDbType.Int, 0, "RegionID"));

    aCommand.Parameters.Add(newSqlParameter("@RegionDescription", SqlDbType.NChar,50, "RegionDescription"));

    aCommand.UpdatedRowSource =UpdateRowSource.None;

    aCommand.Parameters[0].Value = 999;aCommand.Parameters[1].Value = "SouthWesternEngland"; aCommand.ExecuteNonQuery();

  • 8/6/2019 Ado.net 2.0 Day1

    27/28

    Procedure that returns output

    parametersCREATE PROCEDURE RegionInsert(@RegionDescriptionNCHAR(50), @RegionID INTEGEROUTPUT)

    AS

    SET NOCOUNT OFF

    SELECT @RegionID = MAX(RegionID)+ 1 FROM Region

    INSERT INTO Region(RegionID, RegionDescription)VALUES(@RegionID, @RegionDescription)

    GO

  • 8/6/2019 Ado.net 2.0 Day1

    28/28

    Calling from .NetSqlCommand aCommand = newSqlCommand("RegionInsert" , conn);aCommand.CommandType =CommandType.StoredProcedure;aCommand.Parameters.Add(new

    SqlParameter("@RegionDescription" , SqlDbType.NChar ,50 , "RegionDescription"));aCommand.Parameters.Add(newSqlParameter("@RegionID" , SqlDbType.Int, 0 ,ParameterDirection.Output , false , 0 , 0 , "RegionID" ,DataRowVersion.Default , null));

    aCommand.UpdatedRowSource =UpdateRowSource.OutputParameters;aCommand.Parameters["@RegionDescription"].Value ="SouthWest";aCommand.ExecuteNonQuery();int newRegionID = (int)

    aCommand.Parameters["@RegionID"].Value;