简体   繁体   中英

Insert empty DateTime from C# into FoxPro

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));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM