Solved

SqlClient.SqlDataAdapter(strSQL, connection) - with a Date as a string :(

Posted on 2006-10-28
9
622 Views
Last Modified: 2008-02-01
I have made a simple form with a Crystal Reports control embedded, with the simple simple code below to bind some data to it.
=====================================

  Dim daT1, daT2 As SqlClient.SqlDataAdapter
        Dim LACARSDataSet As DataSet
        Dim strSQL As String
        Dim connection As New SqlConnection(DataDB.GetConnStr)
        connection.Open()

        LACARSDataSet = New DataSet


        strSQL = "SELECT * FROM client WHERE ClientID = '" & intClientID & "'"
        daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT2.Fill(LACARSDataSet, "client")


        strSQL = "SELECT * FROM driver"
        daT1 = New SqlClient.SqlDataAdapter(strSQL, connection)
        daT1.Fill(LACARSDataSet, "driver")

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToShortDateString() & "' AND PickupDateTime < '" & dtTo.ToShortDateString() & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If



        Dim rpt As New ClientsReport
        rpt.SetDataSource(LACARSDataSet)
        CrystalReportViewer1.ReportSource = rpt

        connection.Close()


=====================================

If you look in the " If AllThisMonth Then" if statement you will see that with this simple code I am trying to display only a specific date range in the Crystal Report.

However...

strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToShortDateString() & "'"

Creating an SQL string like this would work well in something that queries a DB directly, BUT
with the SqlDataAdapter, I have compile errors with the date string if its not in .ToShortDateString and when it is it plain just doesnt have an effect.
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")

I can only assume that SqlClient.SqlDataAdapter(strSQL, connection) does not know who to convert a sstring of a Date into an actual date as I would be able to normally.

I've explained this poorly, but I've no real understanding of why the DataSet wont fill the data with the correct time-relevent records and why with this simple code (i am new to CR and merely want this one report to show with no hassle) the date cant be read as a string.

I hope someone understands my ramblings and can help. Thanks.
0
Comment
Question by:deecree
  • 2
  • 2
  • 2
9 Comments
 
LVL 41

Expert Comment

by:graye
ID: 17829393
The DateTime format for SQL Server wants the "medium" date format

.ToString("MMM d yyyy")

0
 

Author Comment

by:deecree
ID: 17829538
System.Data.SqlClient.SqlException was unhandled
  Class=16
  ErrorCode=-2146232060
  LineNumber=1
  Message="Conversion failed when converting datetime from character string."
  Number=241
  Procedure=""
  Server="localhost"
  Source=".Net SqlClient Data Provider"
  State=1
  StackTrace:
       at System.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
       at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj)
       at System.Data.SqlClient.TdsParser.Run(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj)
       at System.Data.SqlClient.SqlDataReader.HasMoreRows()
       at System.Data.SqlClient.SqlDataReader.ReadInternal(Boolean setTimeout)
       at System.Data.SqlClient.SqlDataReader.Read()
       at System.Data.Common.DataAdapter.FillLoadDataRow(SchemaMapping mapping)
       at System.Data.Common.DataAdapter.FillFromReader(DataSet dataset, DataTable datatable, String srcTable, DataReaderContainer dataReader, Int32 startRecord, Int32 maxRecords, DataColumn parentChapterColumn, Object parentChapterValue)
       at System.Data.Common.DataAdapter.Fill(DataSet dataSet, String srcTable, IDataReader dataReader, Int32 startRecord, Int32 maxRecords)
       at System.Data.Common.DbDataAdapter.FillInternal(DataSet dataset, DataTable[] datatables, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, Int32 startRecord, Int32 maxRecords, String srcTable, IDbCommand command, CommandBehavior behavior)
       at System.Data.Common.DbDataAdapter.Fill(DataSet dataSet, String srcTable)
       at LACARS.ReportsClients.DoReport() in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 48
       at LACARS.ReportsClients.btnGo_Click(Object sender, EventArgs e) in C:\Documents and Settings\Administrator\My Documents\Visual Studio 2005\Projects\LACARS\LACARS\ReportsClients.vb:line 116
       at System.Windows.Forms.Control.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnClick(EventArgs e)
       at System.Windows.Forms.Button.OnMouseUp(MouseEventArgs mevent)
       at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
       at System.Windows.Forms.Control.WndProc(Message& m)
       at System.Windows.Forms.ButtonBase.WndProc(Message& m)
       at System.Windows.Forms.Button.WndProc(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
       at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
       at System.Windows.Forms.NativeWindow.DebuggableCallback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
       at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
       at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(Int32 dwComponentID, Int32 reason, Int32 pvLoopData)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
       at System.Windows.Forms.Application.Run(ApplicationContext context)
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.OnRun()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.DoApplicationModel()
       at Microsoft.VisualBasic.ApplicationServices.WindowsFormsApplicationBase.Run(String[] commandLine)
       at LACARS.My.MyApplication.Main(String[] Args) in 17d14f5c-a337-4978-8281-53493378c1071.vb:line 81
       at System.AppDomain.nExecuteAssembly(Assembly assembly, String[] args)
       at System.Runtime.Hosting.ManifestRunner.Run(Boolean checkAptModel)
       at System.Runtime.Hosting.ManifestRunner.ExecuteAsAssembly()
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext, String[] activationCustomData)
       at System.Runtime.Hosting.ApplicationActivator.CreateInstance(ActivationContext activationContext)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssemblyDebugInZone()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
==========================

This gives me this above exception at line;
            daT2.Fill(LACARSDataSet, "job")

in this If statement...

        If AllThisMonth Then
            'strSQL = "SELECT * FROM job WHERE PickupDateTime > DateAdd(Month, -2, " & DateTime.Now().ToShortDateString() & ")"
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & DateTime.Now().AddMonths(-2).ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        Else
            strSQL = "SELECT * FROM job WHERE PickupDateTime > '" & dtFrom.ToString("MMM d yyyy") & "' AND PickupDateTime < '" & dtTo.ToString("MMM d yyyy") & "'"
            daT2 = New SqlClient.SqlDataAdapter(strSQL, connection)
            daT2.Fill(LACARSDataSet, "job")
        End If

====================

This is the exception i was alluding at in the first post.
0
 
LVL 41

Expert Comment

by:graye
ID: 17829591
Humph... that should have worked.

Add a break (or a debug.print) to display the final value for strSQL to make sure it appears formatted correctly.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 

Author Comment

by:deecree
ID: 17829894
SELECT * FROM job WHERE PickupDateTime > 'jul 29 2006' AND PickupDateTime < 'oct 29 2006'

I believe this is correct. I have been working on this on and off for about 2 weeks now and growing extremely bitter. Please help.
0
 
LVL 35

Accepted Solution

by:
YZlat earned 500 total points
ID: 17833663
did you try changing it to

SELECT * FROM job WHERE PickupDateTime BETWEEN 'jul 29 2006' AND  'oct 29 2006'

or

or

SELECT * FROM job WHERE PickupDateTime BETWEEN '07/27/2006' AND '10/29/2006'


SELECT * FROM job WHERE PickupDateTime > '07/27/2006' AND PickupDateTime < '10/29/2006'
0
 
LVL 35

Expert Comment

by:YZlat
ID: 17833679
BETWEEN is better to use than <
0

Featured Post

Do You Know the 4 Main Threat Actor Types?

Do you know the main threat actor types? Most attackers fall into one of four categories, each with their own favored tactics, techniques, and procedures.

Join & Write a Comment

For those of you who don't follow the news, or just happen to live under rocks, Microsoft Research released a beta SDK (http://www.microsoft.com/en-us/download/details.aspx?id=27876) for the Xbox 360 Kinect. If you don't know what a Kinect is (http:…
Real-time is more about the business, not the technology. In day-to-day life, to make real-time decisions like buying or investing, business needs the latest information(e.g. Gold Rate/Stock Rate). Unlike traditional days, you need not wait for a fe…
Excel styles will make formatting consistent and let you apply and change formatting faster. In this tutorial, you'll learn how to use Excel's built-in styles, how to modify styles, and how to create your own. You'll also learn how to use your custo…
You have products, that come in variants and want to set different prices for them? Watch this micro tutorial that describes how to configure prices for Magento super attributes. Assigning simple products to configurable: We assigned simple products…

747 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

9 Experts available now in Live!

Get 1:1 Help Now