I have a C# application over MySql, using MySQL Connector; I'm trying to make a
DataReader request, the query executes fine, however, when trying to access a DateTime field, i'm getting MySqlConversionException {"Unable to convert MySQL date/time value to System.DateTime"}
this is the prototype
if (dr != null && !dr.Read()) return;
sesion.Id = Convert.ToInt32(dr["id"]);
sesion.Usuario = Convert.ToInt32(dr["usuario"]);
sesion.Estado = Convert.ToByte(dr["estado"]);
// doesn't work
sesion.FchCreacion = Convert.ToDateTime(dr["fch_creacion"]);
Any suggestions?
Thanks in advance
This error sometimes occurs if you have zero datetime values in your MySQL database (00/00/0000 00:00). Try adding this to the end of your connection string:
Allow Zero Datetime=true
There are a few potential gotchas when converting between MySQL dates/times and .NET DateTimes, but there's a useful section in the MySQL documentation with advice on how to handle the issues.
I'd suggest it may be a culture specific error - is the applicaiton on the same server as the DB, and do they have the same culture settings?
Also, is the column definitely a datetime in MySQL?
It could also be a DBNull value.
Related
I know the question is a bit confusing. Please let me elaborate.
Suppose
I have a table student master which has a column DOB
I have inserted a record and in DOB I have inserted '1991-01-01'
running select statement from sql server is returning date in the same format as it is inserted '1991-01-01' but when I am running the same query from C# using SqlDataAdapter then its returning date as '01-01-1991'
Can anyone explain why it is happening and is there any way to fetch the date in same format as it is inserted.
Query
Is it possible to get the DateTime using SqlDataAdapter as it was inserted?
P.S: column data type is Datetime
let's separate the wheat from the chaff :)
if for your needs meaningful is data type (datetime in this case), then formatting does not matter at all. All layers which will exchange or process the data will use data type information for that.
But
if the meaningful part is formatting, i.e. string representation of the data, then you need to consider the appropriate settings of UI tools you use to display your data. SSMS, for example, uses regional settings for that. If you need to visualize data in the identical manner, so you need the identical strings, you should take care of formatting by your self or in another words, you need to convert your datetime data to string in the same way in all places where you need it.
In T-SQL, for example, you could use CAST and CONVERT functions for formatting your data in a format you need.
If you can't match up the "Cultures" between the SQL Server and the machine you're building the application on (and, in fact, you cannot rely on that really if you're application is going to be deployed to other machines!), then the cheap and quick way round it is to run your date returns through a parse function such as this:
private string FncFormatDate(string date)
{
DateTime formattedDate;
if (DateTime.TryParse(date, out formattedDate))
{
return formattedDate.ToString("yyyy-MM-dd");
}
else
{
return "Invalid date";
}
}
I hope this answers your question.
I've got the error:
INPUT STRING WAS NOT IN A CORRECT FORMAT
when running the code below.
So what do you think here is the error? How will I format the date in the DateTimePicker to store properly in MySQL database?
Here is my code (I included only the relevant code which I think is the error):
cmd.Parameters.AddWithValue("#Rdate", _order.dateTimePicker_Requested.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#Ndate", _order.dateTimePicker_Needed.Value.ToString("yyyy-MM-dd"));
cmd.Parameters.AddWithValue("#CodeDate", Convert.ToDateTime(DateTime.Now).ToString("yyyy-MM-dd hh:mm:ss"));
Unless your MySQL columns are strings (which they shouldn't be), you should be passing actual dates as parameters.
Don't call .ToString().
You should set :
string.Format("{0:yyyy-MM-dd}", your_date);
Hope this helps!
If your variable represents datetime value then its no need to convert it to string it automatically mapped with MySQL column type and if it still not work then reply.
I will post with some code that will convert datetime to proper so that it would mapped with column.
Thank you.
I am playing around with Sqlite and keep getting an error when trying to read back some test data. For example, I created a simple db with a single table and some columns and populated it with some test data as shown below.
sqlite> .schema
CREATE TABLE "shows"(id integer primary key asc autoincrement, showName TEXT, guest TEXT, dateAired date, dateWatched date);
sqlite> select * from shows;
6|test show|test guest 1|2012.05.01|2012.07.10
7|test show|test guest 2|2012.05.02|2012.07.10
8|test show|test guest 4|2012.05.04|2012.07.10
I am using the System.Data.Sqlite library available here , but it keeps giving me an error while trying to read the date column. I tried putting the dates in the dd-MM-yyyy format, but still get an error saying "String Not Recognized as a valid datetime." I have tried using DateTime.Parse or casting it to datetime or just ToString()'ing it to see what happens, but I keep getting the same error. I can read the text fields fine, but can't read the date fields.
My C# code snipped is given below
var sqliteConn = new SQLiteConnection("Data Source=data/shows.db;Version=3;New=False;Compress=True");
sqliteConn.Open();
SQLiteCommand cmd = new SQLiteCommand(sqliteConn);
cmd.CommandText = "select * from shows";
SQLiteDataReader reader = cmd.ExecuteReader( );
while (reader.Read( ))
{
var showName = reader["showName"];
// This is where it keeps giving me an error.
// I have tried various things such as DateTime.Parse
var airedDate = DateTime.ParseExact("yyyy.MM.dd", reader["dateAired"].ToString(), new CultureInfo("en-AU"));
}
reader.Close( );
Any help would be greatly appreciated.
Regards,
Based on the discussion in this thread, I decided to construct my connection string with the "datetimeformat" parameter and the "String Not Recognized as a valid datetime" issue was resolved.
My example connection string:
source=<source to db file>;version=3;new=False;datetimeformat=CurrentCulture
This feature was released in version 1.0.87.0 on July 8, 2013 (see release notes)
This thread might be a bit old but I came across the same problem and found a "solution".
It seems that System.Data.SQLite does not handle DateTimes correctly. I tried DateTime.ParseExact and gave the format in my database (mm/dd/yyyy) but I noticed that it threw an error when just calling ToString() on the DataReader column for the date. This seemed strange since I was not attempting to fit it into a Date but have it read out as a String.
Because of this, I went back to the view I was calling from the database and wrapped all of my dates in a CAST as nvarchar(10). This way, the database will return strings and not dates. Now, the DateTime.Parse works just fine!
I'll use a trigger on the view to pull the string/date back in and insert/update the underlying tables, thus having all the conversions happen in the database, instead of System.Data.SQLite.
There is a new version of System.Data.SQLite coming sometime in December of 2012, I hope this is addressed!
select strftime('%m/%d/%Y',substr(colName,0,20)) from tablename
This will work, I have tested this, because built in functions in sqlite converts string to datetime format
Changing the string for connection didn't work for me but the trigger idea help me use it this way
"Select Cast("Coulname" as nvarchar(20)) From "Table Name"
Error "String was not recognized as a valid DateTime."
Change your system date time format to you database fild datetime format.
i hope it help you....
I am currently developing a C# MySQL Export Utility. Due to this I am not going to know the fields or the data types of each field in the table.
When I export the data from the table in the database it displays a MySQLConversionException stating that it is unable to Covert MySQL Date/Time to System.DateTime. It was doing this when I ran the code:
if (!reader.isDBNull(fieldCount)){}
However, when the exception was thrown on this line I fixed it by adding Allow Zero DateTime=true to the MySQL Connection string but not it is displaying the error when I run the code
string value = reader.getString(field);
How can I get around this issue bearing in mind I am not going to know what data type is or what the value is going to be.
Thanks for any help you can provide.
You can get the raw value as object:
object value = reader[field];
Then decide what to do based on its type:
if (value is string)
{
string sVal = value.ToString();
//handle as string...
}
else if (value is DateTime)
{
DateTime dtVal = (DateTime)value;
//handle as DateTime...
}
else
{
//some other type
}
Maybe not elegant, but should work.
If you read DATETIME values with MySQL Connector/Net and set 'Allow Zero Datetime', then you should use the reader.GetValue() method; in this case the reader will return a MySqlDateTime object with '0000-00-00 00:00:00' value.
Connector/Net Connection String Options Reference
Note, than .NET DateTime.MinValue = 00:00:00.0000000, January 1, 0001.
Also, try dotConnect for MySQL components.
I tackled a problem similar to this in an old open source project of mine. See it here in my Util.DefaultConvert() method.
The trick is to use Type.GetTypeCode() and switch on the result.
Then implement a strict conversion for each type. There is most likely other code in there you can check out to do what you need. I have a MySql provider in there as well.
How does one use the SQL time datatype introduced in SQL Server 2008 in C#.NET?
I've been trying to get it to work but no success.
Here is an MSDN article that reviews all the new Date and Time datatypes introduced in SQL Server 2008 with respect to ADO.NET. As the document says: For System.Data.DbType.Time you would use the .NET Framework type System.TimeSpan
I think you can use TimeSpan datatype for your purpose.
Here is an article that explains the use of Time datatype in ADO.NET.
Also even people from Microsoft tend to recommend mapping the sql datatype time to System.Timestamp I would not recommend doing so,
since the range of sql time is 00:00:00.0000000 - 23:59:59.9999999
wheras the range of System.TimeSpan is 10675199.02:48:05.4775808 - 10675199.02:48:05.4775807
which is just slightly different and can lead to nasty runtime out of range errors.
you can read it using datareader using something similar to following statement .
TimeSpan time = dr.GetTimeSpan(dr.GetOrdinal(“Time7FieldName”));
How are you accessing the data? Using Entity Frameworks, StoredProcedures etc.
If you have to pass a string representation of the date make sure that you do it in the format "yyyy-mm-dd hh:mm:ss" otherwise you will run the risk of the dd/mm/yyyy vs mm/dd/yyyy confusion.
If you are using Entity Framework or DataSets then you should just pass the parameter a DataTime instance eg DateTime.Now
if your field is in time u can simply cast with (Timespan),
while (reader.Read())
{
TimeSpan DBStartTime = (TimeSpan)reader["StartTime"];
TimeSpan DBEndTime = (TimeSpan)reader["EndTime"];
}