Object-oriented programming 2 Final.pptx

  • Upload
    psywar

  • View
    215

  • Download
    0

Embed Size (px)

Citation preview

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    1/37

    OBJECT-ORIENTEDPROGRAMMING 2

    Final term

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    2/37

    WORKING WITH DATES ANDTIME IN C#

    This chapter includesusing objects to work with dates and times in C# baseapplications.

    adding and subtracting time,

    getting the system date and time andformatting and extracting elements of dates and timesC#.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    3/37

    CREATING A C# DATE TIMEOBJECT

    The first step is to create an object instance of DateTime object

    This may achieved using the newkeyword passing through year, monday values.

    For example, to create a DateTime object preset to September 22, 20following code would need to be written:

    class TimeDemo {

    static void Main() {

    DateTime meetingAppt = new DateTime(2014, 9, 22);

    System.Console.WriteLine (meetingAppt.ToString());

    } }

    Output:

    9/22/2014 1

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    4/37

    CREATING A C# DATE TIMEOBJECT

    using System;

    class TimeDemo {static void Main() {

    DateTime meetingAppt = new DateTime(2014, 9, 22, 14, 30, 0);

    System.Console.WriteLine (meetingAppt.ToString());

    } }

    Ou

    9/2

    DateTime dateFromString = DateTime.Parse("7/10/12014 7:10:24

    AM";);

    DateTime dt1 = Convert.ToDateTime(10/10/2014);

    DATETIME FROM A STRING

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    5/37

    GETTING THE CURRENTSYSTEM TIME AND DATE

    The system date and time of the computer on which the C# code isexecuting may be accessed using the Todayand Nowstatic propertieDateTime class. The Todayproperty will return the current system datalso the time set to 12:00 AM) while the Nowproperty returns the currdate and time.

    using System;

    class TimeDemo {

    static void Main() {

    System.Console.WriteLine (DateTime.Today.ToString()

    System.Console.WriteLine (DateTime.Now.ToString());

    } }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    6/37

    ADDING OR SUBTRACTINGFROM DATES AND TIMES

    Method DescriptionAdd Adds/Subtracts the value of the specified TimeSpan obje

    AddDays Adds/Subtracts the specified number of days

    AddHours Adds/Subtracts the specified number of hours

    AddMilliseconds Adds/Subtracts the specified number of Milliseconds

    AddMinutes Adds/Subtracts the specified number of minutes

    AddMonths Adds/Subtracts the specified number of monthsAddSeconds Adds/Subtracts the specified number of seconds

    AddYears Adds/Subtracts the specified number of years

    static void Main() {

    DateTime meetingAppt = new DateTime(2014, 9, 22, 14, 30, 0);

    DateTime newAppt = meetingAppt.AddDays(5);

    System.Console.WriteLine (newAppt.ToString());

    }

    9/27/2014

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    7/37

    ADDING OR SUBTRACTINGFROM DATES AND TIMES

    DateTime objMyBirthday = new DateTime(1969,7,22);

    DateTime objNewDate = objMyBirthday.AddMonths(6); // 1/22/1970 12:00:0

    objNewDate = objMyBirthday.AddYears(2); // Returns 7/22/1971 12:00:00 A

    objNewDate = objMyBirthday.AddMonths(5); // Returns 12/22/1971 12:00:00

    objNewDate = objMyBirthday.AddHours(7); // Returns 7/22/1969 7:00:00 AM

    To subtract from a date and time simply pass through a negativ

    value to the appropriate method

    DateTime newAppt = meetingAppt.AddMonths(-10);

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    8/37

    C# TIMESPAN

    TimeSpanrepresents a length of time.

    Example calls the TimeSpan constructor with five int arguments. It createwith 1 day, 2 hours, and 30 seconds.

    TimeSpan span = new Time pan(1, 2, 0, 30, 0);

    Console.WriteLine(span);

    Or

    DateTime dt1 = Convert.ToDateTime(textBox1.Text);

    DateTime dt2 = Convert.ToDateTime(textBox2.Text);

    TimeSpan ts = dt2 - dt1;

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    9/37

    C# DATETIME SUBTRACT

    One DateTimecan be subtractedfrom another. This returns the diffein time between the two dates.

    For example, the difference between December 25 and January 1 in t2008 is seven days.

    DateTime christmas = new DateTime(2008, 12, 25);

    DateTime newYears = new DateTime(2009, 1, 1);

    TimeSpan span = newYears.Subtract(christmas);

    Console.WriteLine(span);

    Console.WriteLine("{0} days", span.TotalDays);

    Output

    7.00:00:00

    7 days

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    10/37

    RETRIEVING PARTS OF ADATE AND TIME

    static void Main()

    {

    DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);

    System.Console.WriteLine (meetingAppt.Day);

    System.Console.WriteLine (meetingAppt.Month);

    System.Console.WriteLine (meetingAppt.Year);

    System.Console.WriteLine (meetingAppt.Hour);System.Console.WriteLine (meetingAppt.Minute);

    System.Console.WriteLine (meetingAppt.Second);

    System.Console.WriteLine (meetingAppt.Millisecond);

    }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    11/37

    FORMATTING DATES ANDTIMES IN C#

    There are number of techniques available for extracting and displayinand times in particular formats. Output may be configured using a smanumber of predefined formatting methods or customized with an almoinfinite number of variations using the ToString() method.

    The basic formatting methods operate as follows:

    DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);

    System.Console.WriteLine(meetingAppt.ToLongDateString()); // Monday, Septe

    22, 2008

    System.Console.WriteLine(meetingAppt.ToShortDateString()); // 9/22/2008

    System.Console.WriteLine(meetingAppt.ToShortTimeString()); // 2:30 PM

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    12/37

    FORMATTING DATES ANDTIMES IN C#

    The ToString() method takes as an argument a format string which s

    precisely how the date and time is to be displayed. The following exashows a few of this formats in action. The subsequent table lists all thpossible format variables which may be used:

    DateTime meetingAppt = new DateTime(2008, 9, 22, 14, 30, 0);

    System.Console.WriteLine(meetingAppt.ToString("MM/dd/yy")); // 09/22/08

    System.Console.WriteLine(meetingAppt.ToString("MM - dd - yyyy")); // 09 - 22 -

    System.Console.WriteLine(meetingAppt.ToString("ddd dd MMM yyyy")); // Mon 2

    System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // M

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    13/37

    FORMATTING DATES ANDTIMES IN C#Format Specifier Description

    d The day of the month. Single-digit days will not have a leading zero.dd The day of the month. Single-digit days will have a leading zero.

    ddd The abbreviated name of the day of the week, as defined in AbbreviatedDayN

    dddd The full name of the day of the week, as defined in DayNames.

    M The numeric month. Single-digit months will not have a leading zero.

    MM The numeric month. Single-digit months will have a leading zero.

    MMM The abbreviated name of the month, as defined in AbbreviatedMonthNames.

    MMMM The full name of the month, as defined in MonthNames.

    y The year without the century. If the year without the century is less than 10, thdisplayed with no leading zero.

    yyThe year without the century. If the year without the century is less than 10, th

    displayed with a leading zero.

    yyyy The year in four digits, including the century.

    ggThe period or era. This pattern is ignored if the date to be formatted does not

    associated period or era string.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    14/37

    FORMATTING DATES ANDTIMES IN C#h The hour in a 12-hour clock. Single-digit hours will not have a leading zero.

    hh The hour in a 12-hour clock. Single-digit hours will have a leading zero.

    H The hour in a 24-hour clock. Single-digit hours will not have a leading zero.

    HH The hour in a 24-hour clock. Single-digit hours will have a leading zero.

    m The minute. Single-digit minutes will not have a leading zero.

    mm The minute. Single-digit minutes will have a leading zero.

    s The second. Single-digit seconds will not have a leading zero.

    ss The second. Single-digit seconds will have a leading zero.

    f The fraction of a second in single-digit precision. The remaining digits are trun

    ff The fraction of a second in double-digit precision. The remaining digits are tru

    fff The fraction of a second in three-digit precision. The remaining digits are trunc

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    15/37

    FORMATTING DATES ANDTIMES IN C#ffff The fraction of a second in four-digit precision. The remaining digits are truncatefffff The fraction of a second in five-digit precision. The remaining digits are truncated

    ffffff The fraction of a second in six-digit precision. The remaining digits are truncated

    ffffff

    fThe fraction of a second in seven-digit precision. The remaining digits are trunca

    t The first character in the AM/PM designator defined in AMDesignator or PMDesi

    tt The AM/PM designator defined in AMDesignator or PMDesignator, if any.

    zThe time zone offset ("+" or "-" followed by the hour only). Single-digit hours will n

    leading zero. For example, Pacific Standard Time is "-8".

    zz

    The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will h

    leading zero. For example, Pacific Standard Time is "-08".

    zzz

    The full time zone offset ("+" or "-" followed by the hour and minutes). Single-digi

    minutes will have leading zeros. For example, Pacific Standard Time is "08:00". :

    time separator defined in TimeSeparator. / The default date separator defined in

    DateSeparator.

    % c- Where c is a format pattern if used alone. The "%" character can be omitted if th

    pattern is combined with literal characters or other format patterns.

    \ c - Where c is any character. Displays the character literally. To display the backslause "\\".

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    16/37

    DATABASE PROGRAMMINGC#

    This chapter includes working in data in C#. Topics includesADO.NET concepts and objects

    Learn what ADO.NET is.

    Understand what a data provider is.

    Understand what a connection object is.

    Understand what a command object is.

    Understand what a DataReader object is.

    Understand what a DataSet object is.

    Understand what a DataAdapter object is.

    Introduction to LINQ

    Working with MySQL

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    17/37

    WORKING WITH DATABASEUSING ADO.NETADO.NET is a set of classes that expose data access services for .NET Framewprogrammers using various sources such as Microsoft SQL Server, Microsoft AcOracle, XML, etc.

    ADO.NET provides a rich set of components for creating distributed, data-sharinapplications. It is an integral part of the .NET Framework, providing access to relXML, and application data.

    ADO.NET supports a variety of development needs, including the creation of fron

    database clients and middle-tier business objects used by applications, tools, lanor Internet browsers.

    ADO.NET relies on the .NET Framework's various classes to process requests aperform the transition between a database system and the user. The operations typically handled through the DataSetclass.

    ADO.NET is the concept of creating and managing database systems, the DataSserves as an intermediary between the database engine and the user interface

    The ADO.NET classes are found in System.Data.dll, and are integrated with the

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    18/37

    ADO.NET ARCHITECTURE

    ADO.Net provides an architecture for communicating between an appand a data source.

    The data source can be anything that has the required API, but usuaa database server.

    DataSource

    Connection

    Object(ADO.Net)

    DataAdaptor

    Dataset(Local)

    Application

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    19/37

    ADO.NET COMPONENTStwo main components for accessing and manipulating data

    the .NET Framework data providers and are components that have been explicitly designed for data manipulation and fast, forward-only, read-on

    data.

    Connectionobject provides connectivity to a data source.

    The Commandobject enables access to database commands to return data, modify data, run stored and send or retrieve parameter information.

    The DataReaderprovides a high-performance stream of data from the data source.

    Finally, the DataAdapterprovides the bridge between the DataSetobject and the data source.The DataAdapteruses Commandobjects to execute SQL commands at the data source to both loadwith data and reconcile changes that were made to the data in the DataSetback to the data source.

    the DataSet

    explicitly designed for data access independent of any data source

    contains a collection of one or more DataTableobjects consisting of rows and columns of data, and alsforeign key, constraint, and relation information about the data in the DataTableobjects.

    http://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.datatable(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspx
  • 8/10/2019 Object-oriented programming 2 Final.pptx

    20/37

    CHOOSING A DATAREADEROR A DATASET

    Use a DataSet to do the following:

    Cache data locally in your application so that you can manipulate it. If you only neethe results of a query, the DataReader is the better choice.

    Remote data between tiers or from an XML Web service.

    Interact with data dynamically such as binding to a Windows Forms control or comrelating data from multiple sources.

    Perform extensive processing on data without requiring an open connection to the source, which frees the connection to be used by other clients.

    If you do not require the functionality provided by the DataSet, you caimprove the performance of your application by using the DataReadereturn your data in a forward-only, read-only manner. Although theDataAdapter uses the DataReader to fill the contents of a DataSet (sPopulating a DataSet from a DataAdapter), by using the DataReaderboost performance because you will save memory that would be conthe DataSet, and avoid the processing that is required to create and f

    contents of the DataSet.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    21/37

    ADO.NET DATA PROVIDERSEXAMPLE

    .NET Framework Data Provider for SQL Server (System.Data.SqlCl uses its own protocol to communicate with SQL Server.

    .NET Framework Data Provider for OLE DB (System.Data.OleDb) uses native OLE DB through COM interop to enable data access.

    .NET Framework Data Provider for ODBC (System.Data.Odbc)

    uses the native ODBC Driver Manager (DM) to enable data access.

    .NET Framework Data Provider for Oracle (System.Data.OracleClie enables data access to Oracle data sources through Oracle client connectivity soft

    requires Oracle client software (version 8.1.7 or a later version) on the system befoconnect to an Oracle data source

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    22/37

    SQLCLIENTusing System;

    using System.Data;

    using System.Data.SqlClient;

    class Program

    {

    static void Main(){

    string connectionString =

    "Data Source=(local);Initial Catalog=Northwind;"+ "Integrated Security=true";

    // Provide the query string with a parameter placeholder.

    string queryString =

    "SELECT ProductID, UnitPrice, ProductName from dbo.products "

    + "WHERE UnitPrice > @pricePoint "

    + "ORDER BY UnitPrice DESC;";

    // Specify the parameter value.

    int paramValue = 5;

    // Create and open the connection in a using block. This

    // ensures that all resources will be closed and disposed

    // when the code exits.

    using (SqlConnection connection =

    new SqlConnection(connectionString))

    {

    // Create the Command and Parameter objects.

    SqlCommand command = new SqlCommand(queryString, connection);

    command.Parameters.AddWithValue("@pricePoint", paramValue);

    // Open the connection in a try/catch bloc

    // Create and execute the DataReader, w

    // set to the console window.

    try

    {

    connection.Open();

    SqlDataReader reader = command.Ex

    while (reader.Read())

    {

    Console.WriteLine("\t{0}\t{1}\t{2}",

    reader[0], reader[1], reader[2]);

    }

    reader.Close();

    }

    catch (Exception ex)

    {

    Console.WriteLine(ex.Message);

    }

    Console.ReadLine();

    }

    }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    23/37

    OLEDBusing System;

    using System.Data;

    using System.Data.OleDb;

    class Program

    {

    static void Main(){

    // The connection string assumes that the Access

    // Northwind.mdb is located in the c:\Data folder.

    string connectionString =

    "Provider=Microsoft.Jet.OLEDB.4.0;Data Source="

    + "c:\\Data\\Northwind.mdb;User Id=admin;Password=;";

    // Provide the query string with a parameter placeholder.

    string queryString =

    "SELECT ProductID, UnitPrice, ProductName from products "

    + "WHERE UnitPrice > ? "

    + "ORDER BY UnitPrice DESC;";

    // Specify the parameter value.

    int paramValue = 5;

    // Create and open the connection in a using block. This

    // ensures that all resources will be closed and disposed

    // when the code exits.

    using (OleDbConnection connection =

    new OleDbConnection(connectionString))

    {

    // Create the Command and Parameter objects.

    OleDbCommand command = new OleDbCommand(queryString, connection);

    command.Parameters.AddWithValue("@pricePoint", paramValue);

    // Open the connection in a try/catch block.// Create and execute the DataReader, writin

    // set to the console window.

    try

    {

    connection.Open();

    OleDbDataReader reader = command.Exe

    while (reader.Read())

    {

    Console.WriteLine("\t{0}\t{1}\t{2}",

    reader[0], reader[1], reader[2]);

    }

    reader.Close();

    }catch (Exception ex)

    {

    Console.WriteLine(ex.Message);

    }

    Console.ReadLine();

    }

    }

    ODB

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    24/37

    ODBCusing System;using System.Data;

    using System.Data.Odbc;

    class Program

    {

    static void Main()

    {

    // The connection string assumes that the Access

    // Northwind.mdb is located in the c:\Data folder.

    string connectionString =

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

    + "Dbq=c:\\Data\\Northwind.mdb;Uid=Admin;Pwd=;";

    // Provide the query string with a parameter placeholder.

    string queryString =

    "SELECT ProductID, UnitPrice, ProductName from products "

    + "WHERE UnitPrice > ? "

    + "ORDER BY UnitPrice DESC;";

    // Specify the parameter value.

    int paramValue = 5;

    // Create and open the connection in a using block. This

    // ensures that all resources will be closed and disposed

    // when the code exits.

    using (OdbcConnection connection =

    new OdbcConnection(connectionString))

    {

    // Create the Command and Parameter objects.

    OdbcCommand command = new OdbcCommand(queryString, connection);

    command.Parameters.AddWithValue("@pricePoint", paramValue);

    // Open the connection in a try/catch block.

    // Create and execute the DataReader, writin

    // set to the console window.

    try

    {

    connection.Open();

    OdbcDataReader reader = command.Exec

    while (reader.Read())

    {

    Console.WriteLine("\t{0}\t{1}\t{2}",

    reader[0], reader[1], reader[2]);

    }

    reader.Close();}

    catch (Exception ex)

    {

    Console.WriteLine(ex.Message);

    }

    Console.ReadLine();

    }

    }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    25/37

    ORACLECLIENTusing System;

    using System.Data;

    using System.Data.OracleClient;

    class Program

    {

    static void Main(){

    string connectionString =

    "Data Source=ThisOracleServer;Integrated Security=yes;";

    string queryString =

    "SELECT CUSTOMER_ID, NAME FROM DEMO.CUSTOMER";

    using (OracleConnection connection =

    new OracleConnection(connectionString))

    {

    OracleCommand command = connection.CreateCommand();

    command.CommandText = queryString;

    try{

    connection.Open();

    OracleDataReader reader = command.ExecuteReader();

    while (reader.Read())

    {

    Console.WriteLine("\t{0}\t{1}",

    reader[0], reader[1]);

    }

    reader.Close();

    }

    catch (Exception ex)

    {

    Console.WriteLine(ex.Message

    }

    }

    }

    }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    26/37

    LINQLanguage-Integrated Query (LINQ) enables

    developers to form set-based queries in theirapplication code, without having to use a separatequery language. You can write LINQ queries againstvarious enumerable data sources (that is, a datasource that implements the IEnumerableinterface),such as in-memory data structures, XML documents,SQL databases, and DataSetobjects.

    There are three separate ADO.NET Language-Integrated Query (LINQ) technologies: LINQ to DataSet - LINQ to DataSet provides richer, optimized

    querying over the DataSet

    LINQ to SQL - enables you to directly query SQL Serverdatabase schemas

    LINQ to Entities - allows you to query an Entity Data Model.

    http://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.data.dataset(v=vs.110).aspxhttp://msdn.microsoft.com/en-us/library/system.collections.ienumerable(v=vs.110).aspx
  • 8/10/2019 Object-oriented programming 2 Final.pptx

    27/37

    INTRODUCTION TO LINQQUERIES

    A queryis an expression that retrieves data from a data source. Queriusually expressed in a specialized query language

    Three Parts of a Query Operation Obtain the data source.

    Create the query.

    Execute the query.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    28/37

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    29/37

    LINQ-THE DATA SOURCEIn the previous example, because the data source is an array, it implicitly sugeneric IEnumerableinterface. This fact means it can be queried with L

    query is executed in a foreachstatement,and foreachrequires IEnumerableor IEnumerable. Types thatsupport IEnumerableor a derived interface such as the genericIQueryacalled queryable types.

    XML// Create a data source from an XML document.

    // using System.Xml.Linq;

    XElement contacts = XElement.Load(@"c:\myContactList.xml");

    DatabaseNorthwnd db = new Northwnd(@"c:\northwnd.mdf");

    // Query for customers in London.

    //IQueryable custQuery =

    from cust in db.Customers

    where cust.City == "London"

    select cust;

    http://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/bb351562.aspxhttp://msdn.microsoft.com/en-us/library/bb351562.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/system.collections.ienumerable.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspxhttp://msdn.microsoft.com/en-us/library/9eekhta0.aspx
  • 8/10/2019 Object-oriented programming 2 Final.pptx

    30/37

    LINQ-THE QUERYThe query specifies what information to retrieve from the data source or souOptionally, a query also specifies how that information should be sorted, groshaped before it is returned. A query is stored in a query variable and initiali

    query expression.

    The query expression contains three clauses: from, whereand select.

    The fromclause specifies the data source, the whereclause applies the filter, andthe selectclause specifies the type of the returned elements.

    string[] musicalArtists = { "Adele", "Maroon 5", "Avril Lavigne" };

    IEnumerable aArtists =

    from artist in musicalArtists

    where artist.StartsWith("A")

    select artist;

    foreach (var artist in aArtists)

    {

    Console.WriteLine(artist);

    }

    Keywords used:

    from / in - Specifies the data sou

    where - Conditional boolean exp

    orderby (ascending/descending)

    ascending or descending order

    select - Adds the result to the ret

    group / by - Groups the results b

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    31/37

    MYSQL ADO.NET PROVIDER

    MySqlConnectionis main connection to theMySQL database

    MySqlCommandenables the execution ofany command against the database.

    MySqlDataReaderprovides fast, forward-oread access to the database.

    MySqlDataAdapterserves as an interfacebetween the MySQL data classes and the

    Microsoft DataSet.MySqlParameterused to store dynamicparameters for a command.

    MySqlTransactionused to represent aMySQL transaction.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    32/37

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    33/37

    UNDEFINED MYSQLNAMESPACE IN C#

    After installing MySqlConnector.Net, in your project you would add name space to your C# source code

    using MySql.Data.MySqlClient;

    but, you may get a compiler error that the "MySql" name space is nfound.

    in this case, add a reference to the Connector's DLL file:1. Project -> Add Reference -> Browse

    2. Find the .Net2.0 MySqlData.dll file, ex:

    C:/MySql/MySqlConnector.Net/bin/.Net 2.0/MySqlData.dll

    This should fix the name space problem.

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    34/37

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    35/37

    OPENING THE CONNECTIOAfter creating connection, open it.

    This may throw a MySqlException

    MySqlConnection myconn = null;

    try {

    myconn = new MySqlConnection( connectString );

    myconn.Open();

    }

    catch ( MySqlException e )

    {

    Console.WriteLine("Error connecting to server:"+e.Message)

    }

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    36/37

    CREATING A COMMANDOBJECT

    Use a MySqlCommand object to issue database cmds

    A Command object is like a Java Statement object.

    You can reuse a Command object.

    Requires a Connection object (myconn) as param.

    MySqlCommand cmd =new MySqlCommand("SHOW TABLES;", myconn);

    MySqlDataReader reader = cmd.ExecuteReader( )

    Method of executing command depends on the SQL statement:

    UPDATE, INSERT, DELETE: cmd.ExecuteNonQuery() returns int.

    SHOW (QUERY): cmd.ExecuteReader() returns MySqlDataReader

    Semi-

  • 8/10/2019 Object-oriented programming 2 Final.pptx

    37/37

    PROCESSING QUERY DATAMySqlDataReader has many methods for getting data by columnnumber, column name, or index.

    Iterate over results using (boolean) reader.Read( )

    MySqlDataReader reader = null;

    try{

    reader = cmd.ExecuteReader( );

    if ( reader == null ) {

    Console.WriteLine("ExecuteReader failed");

    return;

    }while( reader.Read() ) {

    Console.WriteLine( reader.GetString(0) ); }

    } catch( MySqlException e) {

    Console.WriteLine("caught exception " + e.Message );

    } finally{

    if (reader != null) reader.Close();

    }