Sunteți pe pagina 1din 37

OBJECT-ORIENTED

PROGRAMMING 2
Final term
WORKING WITH DATES AND
TIME IN C#
This chapter includes
using objects to work with dates and times in C# based
applications.
adding and subtracting time,
getting the system date and time and
formatting and extracting elements of dates and times in
C#.
CREATING A C# DATE TIME
OBJECT
The first step is to create an object instance of DateTime object
This may achieved using the new keyword passing through year, month and
day values.
For example, to create a DateTime object preset to September 22, 2014 the
following 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 12:00:00 AM
CREATING A C# DATE TIME
OBJECT
using System;
class TimeDemo {
static void Main() {
DateTime meetingAppt = new DateTime(2014, 9, 22, 14, 30, 0);
System.Console.WriteLine (meetingAppt.ToString());
} }
Output:

9/22/2014 2:30:00 PM
DateTime dateFromString = DateTime.Parse("7/10/12014 7:10:24
AM";);

DateTime dt1 = Convert.ToDateTime(10/10/2014);
DATETIME FROM A STRING
GETTING THE CURRENT
SYSTEM TIME AND DATE
The system date and time of the computer on which the C# code is
executing may be accessed using the Today and Now static properties of the
DateTime class. The Today property will return the current system date (and
also the time set to 12:00 AM) while the Now property returns the current
date and time.
using System;
class TimeDemo {
static void Main() {
System.Console.WriteLine (DateTime.Today.ToString()
System.Console.WriteLine (DateTime.Now.ToString());
} }
ADDING OR SUBTRACTING
FROM DATES AND TIMES
Method Description
Add Adds/Subtracts the value of the specified TimeSpan object instance.
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 months
AddSeconds 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 14:30:00 PM
ADDING OR SUBTRACTING
FROM DATES AND TIMES
DateTime objMyBirthday = new DateTime(1969,7,22);

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

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

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

objNewDate = objMyBirthday.AddHours(7); // Returns 7/22/1969 7:00:00 AM
To subtract from a date and time simply pass through a negative
value to the appropriate method

DateTime newAppt = meetingAppt.AddMonths(-10);
C# TIMESPAN
TimeSpan represents a length of time.
Example calls the TimeSpan constructor with five int arguments. It creates a TimeSpan
with 1 day, 2 hours, and 30 seconds.
TimeSpan span = new TimeSpan(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;

C# DATETIME SUBTRACT
One DateTime can be subtracted from another. This returns the difference
in time between the two dates.
For example, the difference between December 25 and January 1 in the year
2008 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
RETRIEVING PARTS OF A
DATE 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);
}
Output

22
9
2008
14
30
0
0
FORMATTING DATES AND
TIMES IN C#
There are number of techniques available for extracting and displaying dates
and times in particular formats. Output may be configured using a small
number of predefined formatting methods or customized with an almost
infinite 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, September
22, 2008
System.Console.WriteLine(meetingAppt.ToShortDateString()); // 9/22/2008
System.Console.WriteLine(meetingAppt.ToShortTimeString()); // 2:30 PM
FORMATTING DATES AND
TIMES IN C#
The ToString() method takes as an argument a format string which specifies
precisely how the date and time is to be displayed. The following example
shows a few of this formats in action. The subsequent table lists all the
possible 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 - 2008

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

System.Console.WriteLine(meetingAppt.ToString("dddd dd MMMM yyyy")); // Monday September 22 2008
FORMATTING DATES AND
TIMES 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 AbbreviatedDayNames.
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, the year is
displayed with no leading zero.
yy
The year without the century. If the year without the century is less than 10, the year is
displayed with a leading zero.
yyyy The year in four digits, including the century.
gg
The period or era. This pattern is ignored if the date to be formatted does not have an
associated period or era string.
FORMATTING DATES AND
TIMES 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 truncated.
ff The fraction of a second in double-digit precision. The remaining digits are truncated.
fff The fraction of a second in three-digit precision. The remaining digits are truncated.
FORMATTING DATES AND
TIMES IN C# ffff The fraction of a second in four-digit precision. The remaining digits are truncated.
fffff 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
f
The fraction of a second in seven-digit precision. The remaining digits are truncated.
t The first character in the AM/PM designator defined in AMDesignator or PMDesignator, if any.
tt The AM/PM designator defined in AMDesignator or PMDesignator, if any.
z
The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will not have a
leading zero. For example, Pacific Standard Time is "-8".
zz
The time zone offset ("+" or "-" followed by the hour only). Single-digit hours will have a
leading zero. For example, Pacific Standard Time is "-08".
zzz
The full time zone offset ("+" or "-" followed by the hour and minutes). Single-digit hours and
minutes will have leading zeros. For example, Pacific Standard Time is "08:00". : The default
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 the format
pattern is combined with literal characters or other format patterns.
\ c
- Where c is any character. Displays the character literally. To display the backslash character,
use "\\".
DATABASE PROGRAMMING IN
C#
This chapter includes working in data in C#. Topics includes
ADO.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
WORKING WITH DATABASE
USING ADO.NET
ADO.NET is a set of classes that expose data access services for .NET Framework
programmers using various sources such as Microsoft SQL Server, Microsoft Access,
Oracle, XML, etc.
ADO.NET provides a rich set of components for creating distributed, data-sharing
applications. It is an integral part of the .NET Framework, providing access to relational,
XML, and application data.
ADO.NET supports a variety of development needs, including the creation of front-end
database clients and middle-tier business objects used by applications, tools, languages,
or Internet browsers.
ADO.NET relies on the .NET Framework's various classes to process requests and
perform the transition between a database system and the user. The operations are
typically handled through the DataSet class.
ADO.NET is the concept of creating and managing database systems, the DataSet class
serves 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 XML
classes found in System.Xml.dll.
ADO.NET ARCHITECTURE
ADO.Net provides an architecture for communicating between an application
and a data source.
The data source can be anything that has the required API, but usually it is
a database server.

Data
Source
Connection
Object
(ADO.Net)
Data
Adaptor
Dataset
(Local)
Application
ADO.NET COMPONENTS
two 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-only access to
data.
Connection object provides connectivity to a data source.
The Command object enables access to database commands to return data, modify data, run stored procedures,
and send or retrieve parameter information.
The DataReader provides a high-performance stream of data from the data source.
Finally, the DataAdapter provides the bridge between the DataSet object and the data source.
The DataAdapter uses Command objects to execute SQL commands at the data source to both load the DataSet
with data and reconcile changes that were made to the data in the DataSet back to the data source.
the DataSet
explicitly designed for data access independent of any data source
contains a collection of one or more DataTable objects consisting of rows and columns of data, and also primary key,
foreign key, constraint, and relation information about the data in the DataTable objects.

CHOOSING A DATAREADER
OR A DATASET
Use a DataSet to do the following:
Cache data locally in your application so that you can manipulate it. If you only need to read
the 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 combining and
relating data from multiple sources.
Perform extensive processing on data without requiring an open connection to the data
source, which frees the connection to be used by other clients.
If you do not require the functionality provided by the DataSet, you can
improve the performance of your application by using the DataReader to
return your data in a forward-only, read-only manner. Although the
DataAdapter uses the DataReader to fill the contents of a DataSet (see
Populating a DataSet from a DataAdapter), by using the DataReader, you can
boost performance because you will save memory that would be consumed by
the DataSet, and avoid the processing that is required to create and fill the
contents of the DataSet.
ADO.NET DATA PROVIDERS
EXAMPLE
.NET Framework Data Provider for SQL Server (System.Data.SqlClient)
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.OracleClient)
enables data access to Oracle data sources through Oracle client connectivity software
requires Oracle client software (version 8.1.7 or a later version) on the system before you can
connect to an Oracle data source

SQLCLIENT
using 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 block.
// Create and execute the DataReader, writing the result
// set to the console window.
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
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();
}
}
OLEDB
using 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, writing the result
// set to the console window.
try
{
connection.Open();
OleDbDataReader reader = command.ExecuteReader();
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
C
using 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, writing the result
// set to the console window.
try
{
connection.Open();
OdbcDataReader reader = command.ExecuteReader();
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();
}
}
ORACLECLIENT
using 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);
}
}
}
}
LINQ
Language-Integrated Query (LINQ) enables
developers to form set-based queries in their
application code, without having to use a separate
query language. You can write LINQ queries against
various enumerable data sources (that is, a data
source that implements the IEnumerable interface),
such as in-memory data structures, XML documents,
SQL databases, and DataSet objects.
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 Server
database schemas
LINQ to Entities - allows you to query an Entity Data Model.
INTRODUCTION TO LINQ
QUERIES
A query is an expression that retrieves data from a data source. Queries are
usually expressed in a specialized query language
Three Parts of a Query Operation
Obtain the data source.
Create the query.
Execute the query.

EXAMPLE
class IntroToLINQ
{
static void Main()
{
// The Three Parts of a LINQ Query:
// 1. Data source.
int[] numbers = new int[7] { 0, 1, 2, 3, 4, 5, 6 };

// 2. Query creation.
// numQuery is an IEnumerable<int>
var numQuery =
from num in numbers
where (num % 2) == 0
select num;

// 3. Query execution.
foreach (int num in numQuery)
{
Console.Write("{0,1} ", num);
}
}
}
LINQ-THE DATA SOURCE
In the previous example, because the data source is an array, it implicitly supports the
generic IEnumerable<T> interface. This fact means it can be queried with LINQ. A
query is executed in a foreach statement,
and foreach requires IEnumerable or IEnumerable<T>. Types that
support IEnumerable<T> or a derived interface such as the genericIQueryable<T> are
called queryable types.
XML
// Create a data source from an XML document.
// using System.Xml.Linq;
XElement contacts = XElement.Load(@"c:\myContactList.xml");
Database
Northwnd db = new Northwnd(@"c:\northwnd.mdf");
// Query for customers in London.
//IQueryable<Customer> custQuery =
from cust in db.Customers
where cust.City == "London"
select cust;

LINQ-THE QUERY
The query specifies what information to retrieve from the data source or sources.
Optionally, a query also specifies how that information should be sorted, grouped, and
shaped before it is returned. A query is stored in a query variable and initialized with a
query expression.
The query expression contains three clauses: from, where and select.
The from clause specifies the data source, the where clause applies the filter, and
the select clause specifies the type of the returned elements.
string[] musicalArtists = { "Adele", "Maroon 5", "Avril Lavigne" };

IEnumerable<string> 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 source
where - Conditional boolean expression (e.g. i == 0)
orderby (ascending/descending) - Sorts the results into
ascending or descending order
select - Adds the result to the return type
group / by - Groups the results based on a given key
MYSQL ADO.NET PROVIDER
MySqlConnection is main connection to the
MySQL database
MySqlCommand enables the execution of
any command against the database.
MySqlDataReader provides fast, forward-only
read access to the database.
MySqlDataAdapter serves as an interface
between the MySQL data classes and the
Microsoft DataSet.
MySqlParameter used to store dynamic
parameters for a command.
MySqlTransaction used to represent a
MySQL transaction.
GETTING
MYSQLCONNECTOR.NET
You need a MySql "Connector" for .Net applications.
Download from http://dev.mysql.com/downloads/
Run the installer.
The connector registers itself with the "Global Assembly Cache" so that the
DLL can be found.
Difference from Java: Java uses a CLASSPATH to find code; Visual Studio uses Windows
Registry to find resources.
(Optional for visual programming) Add the components to the Toolbox in
Visual Studio:
Tools -> Add/Remove Toolbox Items...
or Tools -> Choose Toolbox Items...
UNDEFINED MYSQL
NAMESPACE IN C#
After installing MySqlConnector.Net, in your project you would add its
name space to your C# source code
using MySql.Data.MySqlClient;
but, you may get a compiler error that the "MySql" name space is not
found.
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.
CREATING A CONNECTION
OBJECT
Connection Object manages the connection to database
server.
You must specify: server name, username, password
Can omit unnecessary attributes or leave blank.
string connectString = "Data Source=localhost;Database=bank;User
Id=bank;Password=FatChance";
MySqlConnection myconn = new MySqlConnection( connectString );
public DBConnection(string host, string database,
string user, string pass) {
string connectString = String.Format(
"Data Source={0};Database={1};User Id={2};Password={3}",
host, database, user, pass);
MySqlConnection myconn = new MySqlConnection( connectString );
}
Better programming:
OPENING THE CONNECTION
After 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);
}
CREATING A COMMAND
OBJECT
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-colon
PROCESSING QUERY DATA
MySqlDataReader has many methods for getting data by column
number, 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();
}

S-ar putea să vă placă și