Click here to Skip to main content
15,886,036 members
Articles / Database Development / SQL Server

Converting Strings to DateTimes for Use in ADO.NET Parameterized Queries using the Data Access Applications Block 3.0

Rate me:
Please Sign up or sign in to vote.
1.75/5 (5 votes)
23 Oct 20042 min read 50K   826   19  
This article shows you how to take a date string and use it in a parameterized sql server query
using System;
using GotDotNet.ApplicationBlocks.Data;
using System.Data;

public class Converter {
	public static void Main( string[] args ) {
		// You can use this if you dont want to deal with typing params at the command line to test
//		IDataReader rdr = GetTheDates( "7/8/1996", "7/9/1996" );
		if( args.Length != 2 ) {
			Console.WriteLine( "Please supply a start and end date" );
			return;
		}
		IDataReader rdr = GetTheDates( args[0], args[1] );
			
		while( rdr.Read() ) {
			Console.WriteLine( "OrderId: {0} - CustomerId: {1}", rdr[ "OrderId" ], rdr[ "CustomerId" ] );
		}
	}

	public static IDataReader GetTheDates( string startdate, string enddate ) {
// COMPILE USING: csc string_datetime_convert.cs /r:GotDotNet.ApplicationBlocks.Data.dll
		string dbcon = "Data Source=localhost; Integrated Security=SSPI;Initial Catalog=northwind";
		SqlServer s = new SqlServer();
		startdate += " 12:00AM";
		enddate += " 11:59PM";
		IDataParameter[] p = new IDataParameter[2];
		p[0] = s.GetParameter( "@StartDate", DateTime.Parse( startdate ));
		p[1] = s.GetParameter( "@EndDate", DateTime.Parse( enddate ));
		string sql = "Select * From Orders WHERE OrderDate BETWEEN @StartDate AND @EndDate";
		return s.ExecuteReader( dbcon, CommandType.Text, sql, p );
	}
}


/*
run:string_datetime_convert.exe
OrderId: 10250 - CustomerId: HANAR
OrderId: 10251 - CustomerId: VICTE
OrderId: 10252 - CustomerId: SUPRD
*/ 

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions