Inserting into DB showing Exception - c#

I am inserting some values into db. In DB field received_date is type of datetime datatype I am using following code for inserting But it is showing some exception, I am unable to figure it out.
Exception:
The conversion of a varchar data type to a datetime data type
resulted in an out-of-range value.
SqlConnection con = new SqlConnection("data source=ATLBLRDP-19\\PRIME;database=arp;uid=sa;pwd=****;");
con.Open();
SqlCommand cmd_r = new SqlCommand();
cmd_r.Connection = con;
cmd_r.CommandType = CommandType.Text;
cmd_r.CommandText = "insert into raw_mails(received_date,sender,receiver,subject,body,has_parsed,has_attachments,created_by,created_on,mail_type) Values(#received_date,#sender,#receiver,#subject,#body,#has_parsed,#has_attachments,'" + DateTime.Now + "','" + DateTime.Now + "',#mail_type)";
cmd_r.Parameters.Add("#received_date", em.DateTimeReceived);
cmd_r.Parameters.Add("#sender", em.From);
cmd_r.Parameters.Add("#receiver", em.Receiver);
cmd_r.Parameters.Add("#subject", em.Subject);
cmd_r.Parameters.Add("#body", em.Body);
cmd_r.Parameters.Add("#has_parsed", 1);
cmd_r.Parameters.Add("#has_attachments", em.HasAttachments);
cmd_r.Parameters.Add("#mail_type", 4);
cmd_r.ExecuteNonQuery();
con.Close();
I checked with every query (parameters.add()) all are working but if I try to insert received_date then only it shows exception . Here em is type of EmailMessage.
And I am using sql server 2012 for DB purpose.

You don't give much to go on, but it is clear that you are setting a date value on your Sql server using a string.
There are definitely two and potentially three places you do this, depending on the type of em.DateTimeReceived. When you build your CommandText you also insert DateTime.Now twice, implicitly calling .ToString() for the conversion.
However, calling .ToString() will use your system's locale. For example, I am in the UK, so today's date (December 13) is written out as "13/12/2013 14:02:08". If I assign this string to a sql datetime it will fail, because my Sql server is using it's default US locale - so it reads 13 as the month and 12 as the day, and throws exactly the error you've seen.
So in order to fix this, you need to either:
output the dates as strings using an explicit format that matches your Sql server's collation (using DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss") or similar)
ensure that all of the dates passed in are actual DateTime variables and not strings, allowing the SqlCommand to ensure formatting is correct

The valid range for the datetime data type is 1753-01-01 through 9999-12-31 (Date and Time Data Types and Functions (technet))
If the em.DateTimeReceived property is smaller than 1753-01-01, you will get this error. Depending on data conversion from .NET to SQL, this might also be the case when DateTimeReceived is null.
Ensure that your property value is always greater than 1753-01-01 or use the datetime2 data type which has a range starting at 0001-01-01.
on a side note: Is there a specific reason you are still using the legacy datetime data type? Microsoft recommends "Use the time, date, datetime2 and datetimeoffset data types for new work. These types align with the SQL Standard. They are more portable. time, datetime2 and datetimeoffset provide more seconds precision. datetimeoffset provides time zone support for globally deployed applications." (msdn)

Either change the DateTime.Now to DateTime.Now.ToString("yyyy/MM/dd HH:mm") or pass them as parameters, similar to your other values.

Related

Datetime conversion giving error

consider me a beginner in c#
I am doing some changes in a pre developed software (C#.Net) , we are saving data by datewise , Currently in insert query (build in c#) we are passing GETDATE() to save today date , but now we have to save data on the basis of a different date.
When I am building query in c# , I m passing that a datetime variable into query
after conversion , conversion as follow
Date_Stamp = DateTime.ParseExact(dt.Rows[0][0].ToString(), "MM/dd/yyyy HH:mm:ss tt", new CultureInfo("en-IN"));
but it is showing error "String was not recognized as a valid DateTime.".
The reason to convert is coz these date field are getting displayed in format ToString("yyyy-MM-dd"));
Which will give 2017-07-13 14:56:30.233 as 13-jul-2017 on front end (as per requirement). We cant change this part of code as it is being used in lot of places , hard to change .
Problem is
variable storing value as
2017-12-07 00:00:00.000
which give after conversion 07-Dec-2017 [wrong - it is needed as 12-jul-2017]
GETDATE storing value as
2017-07-12 14:56:30.233
which is after conversion coming right as 12-jul-2017
I know there is no datetime format in sql server when it come to storing data
But can we store value from variable [2017-12-07 ] as [2017-07-12 ] ?
How GETDATE() give us date in year-month-date format
?
Neither .NET's nor SQL Server's date related type have any format. All of them are binary values, just like integers and decimals. Formats apply only when they are explicitly or implicitly converted to strings, or parsed from strings.
Assuming your query looked something like SELECT GETDATE(), ... and you loaded the results to an DataTable, the values will be returned as DateTime values. If you used a strongly-typed DataTable you could just use the value. With a generic DataTable the value will be boxed and return as an object.
All you have to do is just cast the field value to DateTime :
Date_Stamp = (DateTime)dt.Rows[0][0];
This will also work for date and datetime2 types. datetimeoffset is returned as DateTimeOffset. time is returned as TimeSpan.
The problem in the original is caused because the field value is formatted into a string using the current culture dt.Rows[0][0].ToString() first. Then ParseExact is called trying to parse it using a different format. A simple DateTime.Parse(dt.Rows[0][0].ToString()) would have worked (even though it would be wasteful), since both DateTime.Parse and DateTime.ToString() use the same culture.
UPDATE
Reading date fields from a table has no issues - the values are returned using the appropriate date type. For example, running SELECT StartDate from ThatTable will return DateTime if the table's schema is :
CREATE TABLE ThatTable
(
ID int,
StartDate datetime
)
Problems are caused if, instead of using the correct type, dates are stored as strings in VARCHAR columns. That's a serious bug that needs to be fixed. There is NO assurance that the strings can be parsed to dates at all, or that they follow the same format. It's all too easy for some faulty application code to use eg DateTime.Now.ToString() and store a localized string in there.
Even if the format is the same, it's just wasteful and unreliable. The string takes more storage than the equivalent type, introduces conversion issues, prevents the use of date functions, and the server can't apply date optimizations to queries and indexing.

How to insert ONLY the date (time not included) to ms access database using C#

OleDbCommand command3 = new OleDbCommand();
command3.Connection = connection;
command3.CommandText = "INSERT into AddLoad(ID_Number,Load_Added,Load_Date) values (#ID_Number, #Load_Added,#Load_Date)";
command3.Parameters.AddWithValue("#ID_Number",UserControl_AddLoadConfirmation.INumberValue);
command3.Parameters.AddWithValue("#Load_Added",addbalance);
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
command3.ExecuteNonQuery();
I tried changing the format of my date column (Load_Date) in ms access database to "Short Date" format, when I view all datas to my Datagrid, it still comes with the hour:minute format.
im not sure with the problem maybe it's this code DateTime.Now.ToString()?
If you are going to persist a date or datetime in your database
the type in your database should be datetime (not varchar!)
You should pass DateTime types to your database directly in the command (not a string equivalent)
You should read back a datetime type when querying from the database (not a string equivalent)
So this line
command3.Parameters.AddWithValue("#Load_Date",DateTime.Now.ToString());
Becomes this
command3.Parameters.Add(New OleDbParameter("#Load_Date", OleDbType.Date) { Value = DateTime.Today });
This also ensures that you are passing the correct type to the command so it knows how it is represented in the schema. You really should not call AddWithValue as this does not pass that information in to the command.
Also keep in mind that when working with Ole (ie. access) parameters are positional and not named. That means the order they appear in in the query has to be the same order they appear in within the parameter collection.

Need C# to save date into sql server as sql server datetime e.g. 2016-05-19 12:46:08.610

I need to have C# via Entity Framework save current datetime to sql server into table column of datatype datetime
Was reading that DateTime.Now in C# is not going to be correct ...
so I stumbled across where a guy posted that he was doing this as it saves down to the proper millisecond
System.Data.SqlTypes.SqlDateTime entry2
= new System.Data.SqlTypes.SqlDateTime(new DateTime(dto.LookUpDateTime));
DateTime entry = entry2.Value;
Now I assumed with the Overloads that I should be able to just do this:
System.Data.SqlTypes.SqlDateTime dt
= new System.Data.SqlTypes.SqlDateTime(new DateTime());
However, I get an error in catch block saying 'sqldatatime overflow...`
DateTime dateTime = dt.Value;
rpmuser.lst_pwd_chg_dtm = dateTime;
rpmuser.cre_dtm = dateTime;
Can I use DateTime.Now or what do I need to do to get this SqlDateTime to work?
This is almost certainly because you are trying to store a date that is outside the supported range. On MS SQL Server the datetime field type can hold datetime values in the range 1-Jan-1753 00:00:00 to 31-Dec-9999 23:59:59.997 inclusive. This is narrower than the range explicitly supported by the .NET DateTime type (1-Jan-0001 00:00:00 to 31-Dec-9999 23:59:59 plus a fraction). So any date prior to 1-Jan-1753 will cause that error.
A common problem is when you use either DateTime.MinValue to indicate a specific state of your data but don't filter that to something the SQL field can contain before sending the data to the database. The solution in this case would be to define a suitable lower boundary of the data and define a static value that is lower but still within the SQL range.
If your data needs to include dates and times outside of the valid range for the SQL datetime field type then you might want to use the datetime2 field type which has the same effective range as the .NET DateTime type. Which is unsurprising since it appears to be the same data structure - count of 100ns ticks since 1-1-1.

Convert date type in c# to match sql server 2008 date type

I have retrieved a date from an application and stored it in a DateTime Variable. The format of date is dd/mm/yyyy.
I now want to update a column (with datatype date (yyyy/mm/dd)) in a sql server 2008 database with this date
I have tried the below code, but it's giving me an exception "string was not recognized as valid datetime". Please help to solve this problem.
DateTime date = calExpirydate.SelectedDate;
DateTime date1 = DateTime.ParseExact(date.ToString(), "YYYY/MM/DD", CultureInfo.InvariantCulture);
You don't need to convert it at all if you use parameters (and you should be).
A rough example:
DateTime date = DateTime.Now;
SqlCommand command = new SqlCommand();
command.CommandText = "INSERT INTO table (date) VALUES (#date)";
command.Parameters.Add("#date",SqlDbType.DateTime).Value = date;
I'm using SQL Server here, however the concept is similar across most ADO.NET providers.
Your DateTime variable in the framework is stored in one basic format. The way it appears is just formatting off of the .ToString. It's saying give me your date bit make it look like this. Sql server is similar, it understands the date time variable regardless of how it appears.
If you pass your DateTime as exactly how it is in the framework it will save it correctly. The date and time isn't changing just how it's displayed. Your try parse isn't working though because it's not able to recognize the partial string you're giving it.
You don't even need a new date time variable to see it the way you want. Even if you're successful you will have identical date time variables.
yyyy/MM/dd should be correct
DateTime string format

c# smalldate pass to sql server proc

I am trying to pass date to a sql procedure, the time is being passed, and causing the proc to fail, because the times do not match, c# is passing date 12:00:00 database shows date 00:00:00
so here is my code
public class
datetime dt_value;
get the date from the javascript calendar
DT_Value = Convert.ToDateTime(Request.Form["TextBox_Tracking_ImportDate"]);
try to convert to mm/dd/yyyy
string DT_Value2 = DT_Value.ToString("ddMMyyyy");
pass date to sql
cmd.Parameters.Add(new SqlParameter("#import_date", DT_Value2));
ERROR: Error converting data type nvarchar to smalldatetime.
Just pass the DateTime directly..
cmd.Parameters.AddWithValue("#import_date", DT_Value);
See SQL Server Data Type Mappings
This is the first problem:
string DT_Value2 = DT_Value.ToString("ddMMyyyy");
cmd.Parameters.Add(new SqlParameter("#import_date", DT_Value2));
You're performing a pointless string conversion, and as a result you're corrupting the data. Just don't do it. Always avoid string conversions as far as you possibly can.
Pass the DateTime directly:
cmd.Parameters.Add(new SqlParameter("#import_date", DT_Value));
Or better, specify the type explicitly:
cmd.Parameters.Add("#import_date", SqlDbType.Date).Value = DT_Value;
Or to just take the date part explicitly from the DateTime:
cmd.Parameters.Add("#import_date", SqlDbType.Date).Value = DT_Value.Date;
To be honest though, if your SQL code actually knows that the parameter is a Date rather than a DateTime, there shouldn't even be the concept of a time part. If you could post your SQL, that would help us diagnose that aspect. It's really important to work out the right types to use - it makes life so much simpler.

Categories