using c# datetime in mysql update query - c#

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.

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.

.Net Core 2.0 application is crashing while using a SUBSTRING expression in a SQL query

I have a program that is moving data between two tables in a database. For this, I am using a SQL query and the System.Data.SqlClient package.
All of a sudden, this query throws an error when executing.
SQLCommand.ExecuteNonQuery is throwing:
Conversion failed when converting date and/or time from character string.
I have isolated the line with the conversion to:
AND DATEDIFF(dd,GETDATE(),SUBSTRING(a.date, 1, 10))<14
where a.date is the datetime as varchar. The query is a INSERT-SELECT query, and if I run only the SELECT part, it works. Even more strange is that this query works perfectly fine to run in SSMS both with and without data found.
Have anyone else seen this case lately?
where a.date is the datetime as varchar.
well there's your main problem. If you are storing a date/time: use the appropriate storage type in the database. You have a wide range to choose from, for example date, smalldatetime, datetime and datetime2 - and: SQL Server will know how to correctly understand and work with that data.
Ultimately the problem here is that SUBSTRING(a.date, 1, 10) isn't giving a result that SQL Server understands as a date through implicit string conversion operations. This approach is a: inefficient, and b: brittle (especially between cultures), hence why you simply shouldn't do that. If you store the data appropriately: all the problems will go away.
However! You could also use CONVERT to tell SQL Server to interpret the string as a date/time, explicitly telling it the format you expect (as a number code), so that it stands a chance.
If your a.date (and substring) isn't in one of the supported formats: abandon all hope.
BTW; DATEDIFF(dd,GETDATE(),SUBSTRING(a.date, 1, 10))<14 is probably more efficiently done by way of calculating the start-date/end-date of your range once and just comparing with a comparison operator. GETDATE() won't change per row, so "14 days from now" won't change per row. This would make your query a lot more efficient, especially when combined with the correct date/time format - it becomes:
a.date <= #end -- or < #end, or > #end, or >= #end
which can use an index.
Interesting! "No changes has been made to the code, and no new data has entered the queried table since then."
So the question why it doesn't work as the same way really have a many choice for you
Your code just don't run into the problem date data before.
Application server have something changed like date region/culture so it affect the application way of seeing date when communicate with DB server
the 2. but from DB server e.g. Infra team upgrade/patch the DB server, the configuration is affect so this has problem with date format , update/patching Db cause the build-in functions too have upgraded behavior too!)
The statement in double-quote is false.
System.Data.SqlClient 's feature when process the query ?
and so on...
I think finding the causes just from this little information is the very difficult task.
From my little search ,you really should go diving into the query and data as the others tried to suggest.
Conversion failed when converting date and/or time from character string while inserting datetime

issue with date between c# and sql converting

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.

access mdb date/time issue

I am trying to fetch the record of 3rd june of 2013 from my database which is made in ms access. Dates are stored in the format of dd/MM/yyyy, below is my query
AND (a.Date = #" + date + "#) ) order by e.E_ID asc
But the amazing thing is i have inserted a record on date of 03/06/2013 which is todays date, while it takes it as 6th march 2013, i have corrected my regional settings, still the same issue. Also in my query i am query for matching date i am using dd/MM/yyyy. Is this a bug from microsoft? please help
Dates are stored in the format of dd/MM/yyyy
I suspect they're not. I suspect they're stored in some native date/time format which is doubtless much more efficient than a 10 character string. (I'm assuming you're using an appropriate field type rather than varchar, for example.) It's important to differentiate between the inherent nature of the data and "how it gets displayed when converted to text".
But the amazing thing
I don't see this as amazing. I see it as a perfectly natural result of using string conversions unnecessarily. They almost always bite you in the end. You're not trying to represent a string - you're trying to represent a date. So use that type as far as you possibly can.
You should:
Use parameterized SQL for queries for many reasons - most importantly to avoid SQL injection attacks, but also to avoid unneccessary string conversions of this kind
Specify the parameter value as a DateTime, thus avoiding the string conversion
You haven't specified which provider type you're using - my guess is OleDbConnection etc. Generally if you look at the documentation for the Parameters property of the relevant command class, you'll find an appropriate example. For example, OleDbCommand.Parameters shows a parameterized query on an OleDbConnection. One thing worth noting from the docs:
The OLE DB .NET Provider does not support named parameters for passing parameters to an SQL statement or a stored procedure called by an OleDbCommand when CommandType is set to Text. In this case, the question mark (?) placeholder must be used. [...]
Therefore, the order in which OleDbParameter objects are added to the OleDbParameterCollection must directly correspond to the position of the question mark placeholder for the parameter in the command text.

Escaping various characters in C# SQL from a variable

I'm working a C# form application that ties into an access database. Part of this database is outside of my control, specifically a part that contains strings with ", ), and other such characters. Needless to say, this is mucking up some queries as I need to use that column to select other pieces of data. This is just a desktop form application and the issue lies in an exporter function, so there's no concern over SQL injection or other such things. How do I tell this thing to ignore quotes and such in a query when I'm using a variable that may contain them and match that to what is stored in the Access database?
Well, an example would be that I've extracted several columns from a single row. One of them might be something like:
large (3-1/16" dia)
You get the idea. The quotes are breaking the query. I'm currently using OleDb to dig into the database and didn't have an issue until now. I'd rather not gut what I've currently done if it can be helped, at least not until I'm ready for a proper refactor.
This is actually not as big problem as you may see it: just do NOT handle SQL queries by building them as plain strings. Use SqlCommand class and use query parameters. This way, the SQL engine will escape everything properly for you, because it will know what is the code to be read directly, and what is the parameter's value to be escaped.
You are trying to protect against a SQL Inject attack; see https://www.owasp.org/index.php/SQL_Injection.
The easiest way to prevent these attacks is to use query parameters; http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlparameter.aspx
var cmd = new SqlCommand("select * from someTable where id = #id");
cmd.Parameters.Add("#id", SqlDbType.Int).Value = theID;
At least for single quotes, adding another quote seems to work: '' becomes '.
Even though injection shouldn't be an issue, I would still look into using parameters. They are the simpler option at the end of the day as they avoid a number of unforeseen problems, injection being only one of them.
So as I read your question, you are building up a query as a string in C#, concatenating already queried column values, and the resulting string is either ceasing to be a string in C#, or it won't match stuff in the access db.
If the problem is in C#, I guess you'll need some sort of escaping function like
stringvar += escaped(columnvalue)
...
private static void escaped(string cv) as string {
//code to put \ in front of problem characters in cv
}
If the problem is in access, then
' escapes '
" escapes "
& you can put a column value containing " inside of '...' and it should work.
However my real thought is that, the SQL you're trying to run might be better restructured to use subqueries to get the matched value(s) and then you're simply comparing column name with column name.
If you post some more information re exactly what the query you're producing is, and some hint of the table structures, I'll try and help further - or someone else is bound to be able to give you something constructive (though you may need to adjust it per Jet SQL syntax)

Categories