Insert empty DateTime from C# into FoxPro - c#

I am trying to insert an empty DateTime into a FoxPro database using DbParameter in C#. Our application marries FoxPro data along with SQL Server and .NET models/data.
My current issue is that most of our DateTime types in C# are not nullable, nor should they be. However, most of our legacy data in FoxPro are empty dates (shown as ' / / : : '). I am trying to do an insert into the FoxPro table where I do a check to see if the .NET DateTime meets certain criteria, then inserts an empty date. This last part has proven to be a nightmare.
What I have tried so far:
.Parameters.Add(string.Empty, new DateTime())
The above understandably inserts 01/01/0001 but is not what we want.
.Parameters.Add(string.Empty, "{}")
.Parameters.Add(string.Empty, "{:://}")
.Parameters.Add(string.Empty, "{//}")
.Parameters.Add(string.Empty, "'{}'")
The above all result in
System.Data.OleDb.OleDbException: 'Data type mismatch'.
which makes sense because I'm trying to send a string to a field with DateTime type.
Does anyone know how to insert an empty DateTime into FoxPro?

If I'm understanding you correctly, you're not using a DbParameter, but rather an OleDbParameter, and you're adding them through the OleDbParameterCollection.Add method?
If so, consider that you are using the overload that is .Add(String, Object), and you could instead use the overload that is .Add(String, OleDbType):
.Parameters.Add(string.Empty, OleDbType.Date)
The default value of an OleDbParameter is null, so you don't need to do anything more for your empty dates.
Also, depending on how the column is defined in your FoxPro database schema, it may be appropriate to pass OleDbType.Date, OleDbType.DBDate, OleDbType.DBTime, or OleDbType.DBTimeStamp. The full list of OleDB types is documented here, but I'm not entirely certain how they align to FoxPro's data types.

I believe your second example is close, but you have the Date and Time portions reversed.
It should be .Parameters.Add(string.Empty, "{//::}")
The // represent the Date portion, and the :: the Time portion.

Not sure of your SQL-Insert statement for VFP, but you MAY need to adjust it and do TWO different inserts. One IF a date exists, another if it does not.
For the one that does NOT have a date, I would hard-enter the following (for example where the "?" are the parameter place-holders)
insert into yourTable ( fld1, fld2,..., YourDateField ) values ( ?, ?, ..., ctot('') )
the function CTOT() means character to datetime and an empty string will comply with expected VFP Date/time field.

Work for me.
Parameters.AddWithValue("CreateDate", new DateTime(1899,12,30,0,0,0));

Related

How to retrieve Timestamp value from SQL Server using DataReader

How to retrieve Timestamp value(eg:0x000000048E18B9D8 ) from SQL Server using DataReader? I'm getting an IndexOutOfRangeException when doing like this
DateTime date = reader.GetDateTime(reader.GetOrdinal("Timestamp"));
Can anyone help on this?
Also I want to know how to pass timestamp parameter to stored procedure using .Net code
IndexOutOfRangeException thrown on reader.Getordinal() suggests that a column called Timestamp doesn't exist. Check your column names again, and replace with the actual value. By default, it will be called timestamp, but only if you haven't specified a column name.
You could also try string ts = reader["timestamp"].toString(), and make sure it returns something.
According to MSDN, a TIMESTAMP data type is "8 bytes...[and]... just an incrementing number and does not preserve a date or a time. To record a date or time, use a datetime data type."
Therefore, reader.GetInt64() is probably close, if you really need this value, but byte[] myTimestamp = reader["timestamp"] is probably better.
As far as passing it back to your stored procedure, you can create a new parameter with SqlDbType.Timestamp. The value will be a byte array, or, if you have it stored as a string, you could try something like:
cmd.Parameters.Add("#TimeStampParam", SqlDbType.Timestamp).Value = System.Text.Encoding.ASCII.GetBytes(myTimestampStr);`
(NB: I haven't tested this, but it should be close enough).
Note that TIMESTAMP is deprecated, and ROWVERSION is not the preferred syntax.

Different format for timestamp when using c# datareader

I'm reading a timestamp from a mysql table using an OdbcDataReader. When I look at the data in the table it is in the format 2013-09-12 11:11:09. But the reader seems to read it in the format 12/09/2013 11:11:09.
I then try to insert this into another mysql table but receive the error:
Incorrect datetime value: '12/09/2013 11:11:09' for column 'timestamp'
at row 1
How can I sort out this difference in formatting? Should I be referencing some Unix timestamp value somehow?
The data shouldn't be in the table in any text format. It's just a date and time.
You'll see the format when you convert the data to a string - which you should do as rarely as possible. In particular, when you're inserting the data into a different table, you shouldn't use a formatted value at all - you should use a DateTime in parameterized SQL.
Basically, unless you really need a string representation of the data, you should keep it in the "native" representation (DateTime in this case). Every time you have a conversion to or from text, that's an opportunity for failure. Dates and times are hard enough with time zones etc, without extraneous conversions getting involved.
How are you looking at the data "in the table"? I'm not familiar with the MySQL implementation, but with Oracle and Sql Server datetime values are stored in an unreadable binary format, and translated to a readable timestamp by the query tool. MySQL is likely doing something similar.
try to insert this into another mysql table
If you care about format when you're inserting the data, you're doing something really bad. That's a strong indication you're using a technique that will be vulnerable to sql injection attacks, rather than parameterized queries. If you use parameterized queries, you assign a C# datetime type to the query parameter value directly, and the ADO.Net object handles any formatting you need. At that point, anything you can successfully DateTime.Parse() or DateTime.TryParse() becomes a valid input for your query.

Error when trying to update values in database

I have the following c#/Query:
TrackDuration =TimeSpan.Parse( Request.Form["TrackDuration"].ToString());
string InsertQuery = string.Format("UPDATE tblTracks SET TrackLength={0}, TrackDuration='{1}', TrackName='{2}',TrackDescription='{3}',TrackMap='{4}',DifficultLevel={5},OverallHeight={6},IsCircular='{7}', ForBeginners='{8}',StartPoint='{9}',ParkingPlace='{10}',SeasonOfYear={11},TrackLocation={12}, Images='{13}' WHERE UserID={14}",
TrackLength, TrackDuration, TrackName, TrackDescription, TrackMap, DifficultID, OverallHeight, IsCircular, ForBeginners, StartPoint, ParkingPlace, SeasonID, AreaID, ImageList, UserID);
But I got this error message:
Syntax error in UPDATE statement
Syntax error (missing operator) in query expression
I realy tried to solve this, but I can't.
How can I fix this problem?
Update:
This is the value of the Query:
UPDATE tblTracks SET TrackLength=35, TrackDuration='02:30:00', TrackName='45',TrackDescription='<p>sometext.</p>
',TrackMap='f',DifficultLevel=3,OverallHeight=450,IsCircular='true', ForBeginners='false',StartPoint='<p>קיבוץיסעור </p>
',ParkingPlace='<p>כניסה לקיבוץ יסעור</p>
',SeasonOfYear=1,TrackLocation=3, Images='' WHERE UserID=1
The sql values types are:
TrackLength = number ; TrackDuration = date/time ; TrackName= string ;TrackDescription= string; TrackMap = string; DifficultLevel=number;OverallHeight=number;IsCircular=true/false;ForBeginners=true/false;
StartPoint=string; ParkingPlace=string; SeasonOfYear=number; TrackLocation=number;Images=string
'02:30:00' is not a correct value for datetime DB field, AFAIK. The default format is controlled by date format setting.
Additionally, '20130412' should work in any case, but for datetime field. You need to format the TrackDuration correctly or use CAST/CONVERT. As TimeSpan doesn't contain date part (it represents a duration and not a point in time), you can only make it up (e.g. prepend "20100101") but that is an awful hack.
The proper solution is to use the correct DB field type.
'02:30:00' might work if the field was of time type. Please read some more about time types in SQL Server.
Even better, why don't you use plain integer for the duration in seconds? The duration is not a date anyway.
The much bigger issue is that you are concatenating strings to set the command text, which opens you for SQL injection attack. If I name the racing track a';DROP TABLE tblTracks;-- your database is toast:
UPDATE tblTracks SET TrackLength=35,
TrackDuration='02:30:00',
TrackName='a';DROP TABLE tblTracks;-- ...

Error in inserting statement when inserting

I am working on c# project and using winform.
Here the problem is the query was working previously but now it is not working
Here the todaydate is a datetimePicker which is set to short date format
and my datatype of column is smalldatetime the error i am getting is
The conversion of a nvarchar data type to a
smalldatetime data type resulted in an out-of-range value.
The statement has been terminated.
if i have two date time picker one for date and second for time then how can i insert? please can you guide me
AddWithValue determines the datatype of the parameter from the value you pass.
In your case you are passing a string and thus the parameter is passed to the database as a string not as a datetime expected by the database
you should change that line
cmd.Parameters.AddWithValue("#today", todaydate.Value);
You're currently passing in the text value, which means something else is having to then parse it as a date. Don't do that. Given that you've got a DateTimePicker, you should just use the DateTime value it provides:
cmd.Parameters.AddWithValue("#today", todaydate.Value);
... or create the parameter first with a specific type (SqlDbType.SmallDateTime), then set the value using todaydate.Value. The important point is to avoid the string conversion.
Wherever possible, you should avoid converting values into text. Keep them in their "natural" form (e.g. DateTime in this case) for as much of the time as possible: on input, parse into the natural form, and if you can avoid ever converting to a string, do so!
I think your time7 column in database is smalldatetime and you tried to assign it a string. I don't suggest it.
Try with Add() method like this;
command.Parameters.Add("#today", SqlDbType.SmallDatetime);
command.Parameters["#today"].Value = todaydate.Value;
or you can use AddWithValue() as also like this;
cmd.Parameters.AddWithValue("#today", todaydate.Value);

Date comparison format in stored procedure

I have a sql server 2005 database and a stored procedure that accepts two dates and does some comparisons on the data #start_date_from and #start_date_to both of which are of type DATETIME.
We are using LINQ to call the stored procedures from our code and dragging the stored procedure onto the LINQ surface generates a method call which accepts nullable datetimes.
The problem that I am facing is that our dates from the user interface are entered as dd/MM/yyyy (we're in Australia) and parsed as a C# DateTime.
Once the call to the stored proc occurs it seems to convert it to an american style date. I'm looking for a way to prevent this, hopefully without having to change the datatype of the parameters in the proc.
I have tried using SET DATEFORMAT dmy in the proc but it seems to have no affect, I assume it must need a GO or something to take effect.
I was considering maybe trying some funky formatting/conversion/casting once inside the stored proc but that seemed like a last resort.
I guess also I could change the input parameters to varchars and put the date in an unambigious format.
Within the proc itself the dates are using with the BETWEEN keyword (if that makes any difference).
So what other options (or which of the ones I've outlined) should I go with?
I guess that user input are implicit converted to DateTime? I would say that you need to parse user input to a valid DateTime before calling the SP.
DateTime.Parse("11/12/1981", new CultureInfo("en-US"));
If the culture is different between users you may want to use the current thread's culture:
DateTime.Parse("11/12/1981", System.Threading.Thread.CurrentThread.CurrentUICulture);

Categories

Resources