issue with date between c# and sql converting - c#

so i have a string "09/15/2014" and in c# it converts it to date:
DateTime from = Convert.ToDateTime(fromdate);
this outputs "9/15/2014" and when I send it over to sql I get this:
select convert(varchar, '9/1/2014 12:00:00 AM', 101)
which doesn't work for me because I need to keep any leading zero's.
help?

If you're worried about the string formats for dates with Sql Server, you're doing it wrong. As a comment to another answer indicates, SQL Server internally stores all dates in a machine-optimized numeric format that is not easily human-readable. It only converts them to a human-understandable format for output in your developer tools.
When sending dates to Sql Server, always use query parameters. In fact, when sending any data, of any type, to Sql Server in an SQL statement, always use query parameters. Anything else will not only result in formatting issues like your problem here, but will also leave you crazy-vulnerable to sql injection attacks. If you find yourself using string manipulation to include data of any type into an SQL string from client code, step away from the keyboard and go ask a real programmer how to do it right. If that sounds insulting, it's because it's so hard to understate the importance of this issue and the need to take it seriously.
When retrieving dates from Sql Server, most of the time you should just select the datetime field. Let client code worry about how to format it. Do you want leading zeros? Great! The Sql Datetime column will at some point be available in C# as a .Net DateTime value, and you can use the DateTime's .ToString() method or other formatting option to convert the value to whatever you want, at the client.

SQL queries use a date and time format which goes like this:
2014-09-15
That's year-month-day. As per the comments below, this may be different depending on the collation you have on your database (see Scott's comment for a more accurate way to describe this and get dates into this format).
DateTime's ToString method has an overload which takes a formatting string. So you can pass the format you want the string to be output to. Try it like this:
string queryDate = from.ToString("yyyy-MM-dd");
And see what you get. Use that on your query.
But if you really want this done right, use parameters. Like:
SqlCommand command = new Command(connection, "SELECT * FROM foo WHERE someDate = #date");
command.Parameters.AddWithValue("#date", from);
// where "from" is your DateTime variable from the code you've shown.
This will save you the trouble of DateTime to String conversions.

Related

How to get datetime format of SQL column in C#?

I want to get format of a datetime column to be able to use it in C#. I want to get it and change my variable to this format. I could not find any solution. How to get it? I just want to be able to get the format of existing column and use it as string in C#.
DateTime values in SQL Server are stored as binary values that are not human readable. They are not strings at all.
For C#, you should use the normal .Net primitive DateTime type to talk to the database; NEVER use any string formats; reserve the string for when you output to the user. The ADO.Net library (which also sits underneath other tools like Entity Framework) will efficiently and safely handle transport between your application and SQL Server.
I am building an sql query to search a string value as parameter that comes from frontend.
Great, we can do that. The way we do it to to parse the string to a C# DateTime, and then use the C# DateTime value for the query.
Let me elaborate. I'm worried you're wanting to do something like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= '" + TextBox1.Text "'";
var cmd = new SqlCommand(SQL, connection);
THAT IS NOT OKAY!
It is NEVER okay to use string concatenation to include user data like that. Instead, you must use parameterized queries. And when you do this, one of the things you can do is provide datetime values.
So instead, the code should look more like this:
string SQL = "SELECT * FROM [MyTable] WHERE [DateColumn] >= #MinDate";
var cmd = new SqlCommand(SQL, connection);
cmd.Parameters.Add("#MinDate", SqlDbType.DateTime).Value = DateTime.Parse(TextBox1.Text);
But even this is still a little rough, because users will do all kinds of things when entering a date into a raw textbox. You'll be much better off if you can also provide a datepicker that ensures you get a clean input from the user.
All that said, the SQL language does have specific formats for Datetime literal values. You can pick any of these formats and the database will handle it correctly:
yyyyMMdd HH:mm:ss[.fff]
yyyy-MM-ddTHH:mm:ss[.fff]
yyyyMMdd
Note the above formats are very specific and must be followed exactly, but if you do any of these can be cleanly converted to SQL Server datetime values. But again: this is not how the values are stored internally, the need for this should be relatively rare, and it's definitely NOT something you would EVER do for user input.

using c# datetime in mysql update query

I'm trying to run a query from C# to MySQL (version 5.5.27) using the mysql connector for .net from the MySQL website.
The ultimate goal of the .dll I'm developing is to keep track of the rows that I've read.
The query I use to read the database is:
string strSQL = "SELECT date,ask,bid,volume FROM gbpjpy where `read` = 0";
To read in the date, I have:
DateTime dateTime = mysqlReader.GetDateTime(0);
That works fine.
The table has 5 columns, the last column is called "read". Right after the select query and parsing is done, I execute the following query:
string sqlFormattedDate = dateTime.ToString("yyyy/MM/dd HH:mm:ss");
string query = "UPDATE gbpjpy SET `read` = 1 WHERE `date` = " + sqlFormattedDate;
However, when I check my log, I have the following error:
You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '01:20:08' at line 1.
The first date read in is 2012/08/30 01:20:08 (that's how it appears in the MySQL table, so that's where it gets the 01:20:08).
I've tried var sqlFormattedDate, changing the ToString overload to yyyy-MM-dd (using dashes and not forward slashes) and dateTime.ToString() all to no avail.
Why is MySQL not picking up the entire string?
Basically you should avoid including values in your query directly.
No doubt you could put quotes around the value... but you shouldn't. Instead, you should use paramterized SQL, and put the value in the parameter. That way you don't an error-prone string conversion, you avoid SQL injection attacks (for string parameters), and you separate code from data.
(As an example of how subtly-broken this can be, your current code will use the "current culture"'s date and time separators - which may not be / and :. You could fix this by specifying CultureInfo.InvariantCulture... but it's best not to do the conversion at all.)
Look for documentation of a Parameters property on whatever Command type you're using (e.g. MySqlCommand.Parameters) which will hopefully give you examples. There may even be a tutorial section in the documentation for parameterized SQL. For example, this page may be what you're after.
I suppose you have to put the whole value for the date in quotes. If you actually concatenate your query, it would look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = yyyy/MM/dd HH:mm:ss
That equal sign will only take the value until the first space.
Instead, it should look like
UPDATE gbpjpy SET `read` = 1 WHERE `date` = 'yyyy/MM/dd HH:mm:ss'
This is the particular reason in this case, however, concatenating queries like this leads to a real possibility of SQL injection. As a rule of thumb, you shouldn't do it. You can use parameterized queries and there's probably an API of the .NET connector you are using to do that.
Putting the info in a parameter allows the code to format as it needs. Likely, your original issue may have stemmed from using slashes instead of dashes in your date format. I would assume that slashes can work, but most all of the documentation I've seen has dashes separating dates with MySqlDateTimes.

How to apply Datetime comparison on varchar Datatype in C#

I want to apply datetime comparison on a field which is of type varchar in SQL Server database. I want to know how can i apply this, for example my query is something like this
from Pos in TableName
where Pos.vcr_Value >= Convert.ToDateTime("UserInputDate") //UserInputDate = 02/02/2011
select Pos;
If i try this it works
from Pos in TableName
where Pos.vcr_Value == "UserInputDate" //UserInputDate = 02/02/2011
select Pos;
But this just matches the date i want to get all the records after UserInputDate variable
Note:
This field store variable type of data sometime it save string sometime datetime
As others have said, your database design is fundamentally poor. Given that the column may not even be a date at all, you'd need to use DateTime.TryParse or DateTime.TryParseExact to write something which would work in LINQ to Objects. In LINQ to SQL that won't work as you'd need to use a lambda expression with a block as the body, and that can't be converted into an expression tree.
Furthermore, you've also got the problem of knowing what date format to expect - which is a natural corollary of storing dates in a text-based field instead of as a native date-based field.
If your date format were yyyy-MM-dd (or yyyy/MM/dd) it would be possible to do something which at least approximated the right query, by doing a string comparison, e.g. saying the value had to be between "2011-02-02" and "2099-12-31" for example. Even then it would match values such as "201 this isn't really a date".
If you don't have too many records, you could always do the filtering at the .NET side instead of in SQL - it's not ideal, but if you have to work with a broken schema, it's probably the most reliable option. If at all possible, however, you should change how you store the data.
Fix you database. Convert the varchar field to DateTime
check here There are answers how to convert and compare dates
HTH
Ivo Stoykov
PS: Steve is right. date format kept in DB as varchar is very bad practice!

Convert a string to smalldatetime

I have a string arranged in a way that would match the format yyyy-dd-MM HH:mm:ss
It might look like this 2010-20-12 13:30:00
I need to insert this into a smalldatetime column in SQL Server. The format of the column is
yyyy-MM-dd HH:mm:ss
I need the string to look like this 2010-12-20 13:30:00 or else SQL Server will get the month and day confused.
Thanks for your thoughts
Don't send your data to SQL server using a string to start with. Instead, use a parameterized SQL statement, and get the driver to do the work for you after you specify a DateTime. (See the SqlCommand.Parameters documentation for an example.)
This is how you should deal with pretty much all values - especially those entered by users. As well as not having to worry about formatting, this will prevent SQL injection attacks.
So that just leaves the task of parsing your input string as a DateTime, which is best done with DateTime.ParseExact or DateTime.TryParseExact, depending on whether you want the result of a parsing failure to be an exception or not.
you can try something like this:
//First convert string to DateTime
DateTime dt;
dt = Convert.ToDateTime("2010-20-12 13:30:00");
//Second Convert DateTime to formatted string
string t_time;
t_time = dt.ToString("yyyy-dd-MM hh:mm tt");
HTH.
You shouldn't need to convert to a string. Use a parameterized sql query or a stored procedure and just provide a datetime object as the parameter. The sql command will handle the insert just fine.
If you only have the string, you can turn it into a datetime using DateTime.Parse and a DateTimeFormatInfo (see this documentation for assistance with creating the format info).

executing queries with datetime in WHERE clause

I use sql server 2008 R2 as a data store.
Until now on the test machine I had the english version of the software and used to make queries formatting the datetime field as
fromDate.ToString("MM/dd/yyyy");
now I have deployed the database on another server which is in the italian language. I shall change the format in my code to
fromDate.ToString("dd/MM/yyyy");
Is there a way to make the query in a neutral format?
thanks!
EDIT:
I forgot to mention that I am using NetTiers with CodeSmith. Here's a complete sample
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate.ToString("MM/dd/yyyy"));
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate.ToString("MM/dd/yyyy"));
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);
You should share the code you are using to execute the query, but I guess you are building a SQL query dynamically using string concats to build the query and the arguments. You should rather use a parameterised query then you can pass the data as a date object and no need to converto a string.
For example if your query could be something like this
DateTime fromDate = DateTime.Now;
SqlCommand cmd = new SqlCommand(
"select * from Orders where fromDT = #fromDate", con);
cmd.Parameters.AddWithValue("#fromDate", fromDate);
...
As a good side effect, this will reduce your risk of SQL injection.
Update: After your edit which does change the question context significantly, and I have to admit that I have Zero knowledge of the .netTiers project. But just out of curiosity have you tried just passing the date instances directly as in the following?
AppointmentQuery aq = new AppointmentQuery(true, true);
aq.AppendGreaterThan(AppointmentColumn.AppointmentDate, fromDate);
aq.AppendLessThan(AppointmentColumn.AppointmentDate, toDate);
AppointmentService aSvc = new AppointmentService();
TList<Appointment> appointmentsList = aSvc.Find(aq);
ISO 8601 Data elements and interchange formats — Information interchange — Representation of dates and times allows both the YYYY-MM-DD and YYYYMMDD. SQL Server recognises the ISO specifications.
Although the standard allows both the
YYYY-MM-DD and YYYYMMDD formats for
complete calendar date
representations, if the day [DD] is
omitted then only the YYYY-MM format
is allowed. By disallowing dates of
the form YYYYMM, the standard avoids
confusion with the truncated
representation YYMMDD (still often
used).
I prefer the YYYYMMDD format, but I think that's because I only knew about that to start with, and to me it seems more universal, having done away with characters that might be considered locale specific.
Personally, I always use yyyy-MM-dd. This also makes it sortable as a string.
However, a date is a date is a date. There's no need to change the date to a string. In .NET, user DateTime.

Categories