Top Banner

of 18

Lec_08 [Compatibility Mode]

Apr 09, 2018

Download

Documents

jojeecares
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/8/2019 Lec_08 [Compatibility Mode]

    1/18

    Lecture 8: Contents

    DataReader Difference between connected and disconnected modes of

    Dataset

    data access

    ,in tabular form. Each column represents a particular variable.Each row corresponds to a given member of the data set inquestion.

    A Dataset is a in memory representation of a collection ofDatabase objects including tables. The dataset contains acollection of Tables, Relations etc.

    Can used for manipulating the data remotely and finally updatingthe database with the modified data. It enables disconnectedmeans of working with data. This improves performance byreducing the number of times a database is accessed.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    2/18

    All the related classes like DataSet, DataAdapter, DataTable,DataRow etc are available inside the System.Data

    . :

    using System.Data;

    Working with DataSet:

    Working with dataset can be looked at from two angles:

    . ng ata nto ataset

    2. Render data on screen

    After populating dataset, presentation of data can beeither on a GUI Client Server screen or on an ASP.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    3/18

    Po ulatin DatasetA dataset can be populated in multiple number

    of ways.

    Manually constructed Rows and Tables Data from an XML File ata rom a ata ase

    Manually constructed Rows and Tables

    an existing set of data such as calculations on adatabase, reading from an unconventional data

    data sources to be rendered into an applicationwritten on our .Net framework (including asp .net,c#, vb .net) etc., then we can go for manipulating

    HOME

    t e ata an t en creat ng t e ataset manua y.

  • 8/8/2019 Lec_08 [Compatibility Mode]

    4/18

    Before constructing a dataset in .net manually, it should beprepared by adding datacolumn types to it. The DataTablet us constructe s ou e a e to t e ata et us ng

    DataSet.Tables.Add(DataTable table name) function. This willadd the DataTable with the specific definition of Column types

    .the DataSet as it is capable of holding multiple Databaseobjects at a single point of time.

    ExampleRow= myDataTable.NewRow();

    " " = " "

    ExampleRow["Age"] = 25;

    myDataTable.Rows.Add(ExampleRow);

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    5/18

    Populating DatasetFollowing code connects with database and fills dataset.string strDBConnection = "server=(local);database=DatabaseName;userid=UserName assword=Pwd connection reset=false connectionlifetime=5;Trusted_Connection=Yes;"

    SqlConnection dbConnection = new SqlConnection(strDBConnection);

    s r ng s r e ec q = e ec rom a e ame ;

    dbConnection.Open();

    =

    SqlDataAdapter sqlData = new SqlDataAdapter(cmd);

    DataSet dsSelectData = new DataSet ;

    sqlData.Fill(dsSelectData);

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    6/18

    opu a ng a ase

    Following code can be used to populate dataset from XML file.

    DataSet dsCategory = new DataSet ();

    dsCategory.ReadXml("XML Path in the drive");

    Example:

    myDataSet.ReadXml (@C:\Employees.xml);

    Aforementioned line of code will fill a data set with data fromEmployees.xml file.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    7/18

    a ase n ng

    We can display data in dataset and bind to any data aware controls.SqlConnection conn = new SqlConnection(conStr);

    .SqlDataAdapter adapter = new SqlDataAdapter("SELECT * FROMMyTable", conn);

    DataSet ds = new DataSet();adapter.Fill(ds,"MyTable");

    this.dataGrid1.SetDataBinding(ds,"MyTable");

    txtBox.DataBindings.Add ("Text",dsCust ,"Customers.FirstName");

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    8/18

    DataReaderWe can use the ADO.NET DataReader to retrieve aread-onl , forward-onl stream of data from a

    database. Results are returned as the queryexecutes, and are stored in the network buffer on

    method of the DataReader.

    Using the DataReader can increase applicationperformance both by retrieving data as soon as it

    ,results of the query to be returned, and (bydefault) storing only one row at a time in memory,reducing system overhead.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    9/18

    ata ea er

    After creating an instance of the Command object, we create aDataReader by calling Command.ExecuteReader to retrieve rowsfrom a data source, as shown in the following example.

    SqlDataReader myReader = myCommand.ExecuteReader();

    if (myReader.HasRows){

    while (myReader.Read())Console.WriteLine("\t{0}\t{1}", myReader.GetInt32(0),

    .}else{ Console.WriteLine("No rows returned."); myReader.Close(); }

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    10/18

    Disconnected S stemsOn a disconnected system a subset of the data isdownloaded to the user and the local co is modified,records added or removed, and then the changes are sentback to the server at a later time.

    This reduces SQL server transactions and server load.Disconnected environments also allow other users to use theconnection and improve the performance of applications.The are articularl useful for connections where there islimited bandwidth, i.e. database connections over a slowInternet line.

    data is not always up to date and change conflicts can occur.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    11/18

    Connected Systems

    Connected environments on the otherhand require a constant connection to the

    .

    All transactions are processed on the

    server in real-time meaning that the data.

    This also leads to a more secureenvironment as data is not stored away

    rom e server an oc ng recor s w ea transaction is in process eliminateschange conflicts.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    12/18

    onnecte vs. sconnecte

    As we have said previously, the SqlDataReaderworks in connected mode so each call toSqlDataReader. Read will stream data from the

    server. It is also sequential, so once a record has been

    read, you can't access it again without executing. .

    The time between sqlCon.Open() ands lCon.Close there is a connection to the server.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    13/18

    onnecte vs. sconnecte

    If you application opens the connection on start-up anddoesn't close it until it exits you can cause unnecessaryrecord or table locks.

    The way around this is by using a DataSet which willdownload a local copy of a subset of the main database thatcan be mani ulated and chan es sent back to the server lateron.

    The important thing to remember about connected mode isthat u dates are rocessed as a command is executed.

    Using disconnected methods allow the data to be previewedand further amended before being committed to the server.

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    14/18

    onnecte o e: xamp e

    sqlCon.Open(); // already got connection string

    string commandString = "SELECT * FROM Customers";SqlCommand sqlCmd = new SqlCommand(commandString, sqlCon);SqlDataReader dataReader = sqlCmd.ExecuteReader();

    while (dataReader.Read()){

    Console.WriteLine(String.Format("{0} {1}",dataReader["CompanyName"], dataReader["ContactName"]));

    dataReader.Close();

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    15/18

    Disconnected Mode: Example

    string commandString = "SELECT * FROM Customers";DataSet ds = new DataSet();

    SqlDataAdapter da = new SqlDataAdapter(commandString,connectionString);

    da.Fill(ds,"Customers);

    foreach DataRow dr in ds.Tables 0 .Rows

    {Console.WriteLine(String.Format("{0} {1}", dr[1].ToString(),dr[2].ToString()));

    }

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    16/18

    p at ng n onnecte o e

    Additional SQL commands must be created after the firstreader has been closed, or you will have to create new objects.

    SqlConnection sqlCon = new

    SqlConnection(connectionString);sq on. pen ;

    string commandString = "SELECT * FROM Customers";

    SqlCommand sqlCmd = new SqlCommand(commandString,sqlCon);

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    17/18

    p at ng n onnecte o e

    SqlDataReader dataReader = sqlCmd.ExecuteReader();

    while dataReader.Read{

    Console.WriteLine(String.Format("{0} {1}",

    dataReader["CompanyName"], dataReader["ContactName"]));}dataReader.Close();

    commandString = "UPDATE Customers SET ContactName = 'JaneDoe' WHERE CustomerID = 'ALFKI'";sqlCmd = new SqlCommand(commandString,sqlCon);

    .sqlCon.Close();

    HOME

  • 8/8/2019 Lec_08 [Compatibility Mode]

    18/18

    Updating in Disconnected Mode

    Disconnected updates are processed by manipulating the DataSetobject. The Rows indexers access the record and the field.

    ds.Tables[0].Rows[0][2] = "Jane Doe";

    We also need to specify and Update/Insert command to the dataadaptor to instruct the server how it should update the table.Luckily there is a built in tool to help with this called the

    SqlCommandBuilder.

    SqlCommandBuilder myBuilder = new SqlCommandBuilder(da);da.UpdateCommand = myBuilder.GetUpdateCommand();

    Changes to the DataSet are not committed to the server until theUpdate method is called from the DataAdaptor.

    " "

    HOME