SQL query not producing any results - c#

I have a following SQL query that I run inside C# application. I work with local (no servers) database created in access:
string query = #"SELECT s.TagID, se.SessionID, '" +
DateTime.Now.ToString("MM/dd/yy HH:mm:ss tt") +
"' AS ScanningTime " +
" FROM (((Student s " +
" LEFT JOIN [CourseID-ModuleID] cm ON s.CourseID = cm.CourseID) " +
" LEFT JOIN [ModuleID-SessionID] ms ON ms.ModuleID = cm.ModuleID) " +
" LEFT JOIN [Session] se ON ms.SessionID = se.SessionID) " +
" WHERE s.TagID = #tagNo " +
" AND se.SessionDate = Date() " +
" AND DateAdd('n', -30, [SessionTimeStart]) < #timeNow " +
" AND se.SessionTimeEnd > #Plus30Min ";
Parameters and variables used in the query:
DateTime TimePlus = DateTime.Now.AddMinutes(30);
DateTime now = DateTime.Now;
string Plus30Min = TimePlus.ToString("hh:mm tt");
string timeNow = now.ToString("hh:mm tt");
command.Parameters.Add("tagNo", OleDbType.Integer).Value = tagNo;
command.Parameters.Add("Plus30Min", OleDbType.VarChar).Value = Plus30Min;
command.Parameters.Add("timeNow", OleDbType.VarChar).Value = timeNow;
At the moment, this query runs, but does not produce any results. However, if I delete the line:
" AND DateAdd('n', -30, [SessionTimeStart]) < #timeNow " +
Then the query runs perfectly. This means that there must be something wrong with this line inside the query. Can you see it somewhere? I looked at multiple websites for examples of date query criteria, but I cannot find the mistake, maybe you will be able to help. Thanks in advance.
The only thing I noticed is the ' sign surrounding n. Should i use quotation mark instead? If so, how can I achieve it inside the quotes?

Change your calling code to
DateTime now = DateTime.Now.AddMinutes(30);
and replace the offending line in query text with
" AND SessionTimeStart > #timeNow "
If you need a DateTime.Now somewhere in your code, you could easily obtain again from the same expression. However, I am a bit perplexed by your parameters. They works against Date/Time fields but you pass strings. If the above solution doesn't work try also to change the OleDbType.VarChar to OleDbType.DBTime or DbDate
EDIT Pay attention to the parameter order. You are using OleDB and the name of parameters is meaningless. You should insert the parameters in the parameter collection in the same exact order in which they appears in the query text. The #timenow and Plus30Min should be changed in position.
Your query ends to use the timenow parameter to test the SessioneEndTime and viceversa
command.Parameters.Add("tagNo", OleDbType.Integer).Value = tagNo;
command.Parameters.Add("timeNow", OleDbType.VarChar).Value = timeNow;
command.Parameters.Add("Plus30Min", OleDbType.VarChar).Value = Plus30Min;

Related

C# query not translating to MYSQL

String query6 = "
SELECT p.*,SUM(L.qty)as sales
FROM product p,purchaseLog L
WHERE L.purchaseDate
BETWEEN '"+ startDate.Value.Date.ToString("yyyy-dd-MM") + "'
AND '"+endDate.Value.Date.ToString("yyyy-dd-MM") +"'
AND p.id=l.itemID GROUP BY p.product_name
ORDER BY sales ASC LIMIT " + " " + " " + count + "";
This is the query that I made in Visual Studio. I tried inputting this query manually without variables in phpmyadmin and it works just fine. But for some reason when I write the query down and pass it to a mysqlcommand and mysqldatareader it doesn't detect the date. The count used not work too. But adding space in between the word "limit" and the count made it work.
Is C# trimming some parts of my queries?
This: 'yyyy-dd-MM' is the wrong format. It must be "yyyy-MM-dd". Ideally you'd even prefix this with the word DATE so as to mark the string as a date literal:
" ... WHERE L.purchaseDate BETWEEN DATE '" + startDate.Value.Date.ToString("yyyy-MM-dd") +
"' AND DATE '" + endDate.Value.Date.ToString("yyyy-MM-dd") + "'... "

Error : in my query i am using multiple variables in c#

i am not getting what is the issue in the query probably i am not following the correct way to put the string and char sign , i am inserting the data in c# to local host with where clause please check the query and Error i am getting
Here is the query
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '"+id+ ",s.session,'" + title.Text+",'"+ from.Value.Date.ToString("yyyy-MM-dd")+",'"+to.Value.Date.ToString("yyyy-MM-dd")+ ", c.class_name,'"+x+",'"+x+" from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
Exception image
here the image for exception i am getting after run this query
On your ...'"+x+"... you forgot to close the single quotes. You open them but you never close them after you add the X variable to your query. All SQL is seeing is "'0," which is invalid syntax.
I recommend use SQLparameters to avoid sql injection but your error is you forgot to close the single quotes it shoud be like this '"+cls + "'
String insertQuery = "insert into exam_add (id,session_id,Title,From_date,To_date,class_id,is_Post,is_Lock) select '" + id + "','"+s.session+"','" + title.Text + "','" + from.Value.Date.ToString("yyyy-MM-dd") + "','" + to.Value.Date.ToString("yyyy-MM-dd")+"' , '"+c.class_name+"','" + x + "','" + x + "' from year_session s, classes c where s.id = '1' and c.id='" + cls + "'";
I don't know why you need that on select columns. and you provided insufficient information and code on your question.

C# query doesn't get executed

Currently I am trying to retrieve the contents of all the entries between a specific date in a MySQL database named 'orders'. To achieve this I use the following code:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw'";
dateFrom and dateTill are both variables that contains timestamps.
Everything above works perfectly. The problem that I am facing right now is that I want to check on two print_locations instead of only one. As shown in the code above I only search on 'antw'. The code that I have right now to search on two print_locations is as follows:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and print_location like 'antw' or print_location like 'helm'";
But somehow this doesn't work. I don't get an error the form just freezes and making it unaccessible.
This is probably a simple issue to resolve but I can't seem to solve it. The reason why I am only showing the value of the query variable and not the rest of my code is because everything has worked fine for weeks.
you forgot brackets and you should use parameters to avoid injection attack
string Command = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between #dateFrom and #dateTill and (print_location like 'antw' or print_location like 'helm')";
using (MySqlConnection myConnection = new MySqlConnection(ConnectionString))
{
using (MySqlDataAdapter myDataAdapter = new MySqlDataAdapter(Command, myConnection))
{
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#dateFrom", yourDateFrom));
myDataAdapter.SelectCommand.Parameters.Add(new MySqlParameter("#dateTill", yourdateTill));
DataTable dtResult = new DataTable();
myDataAdapter.Fill(dtResult);
}
}
Add brackets to your logic:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like 'antw' or print_location like 'helm')";
Be careful though... this smells like a potential case of SQL injection!
Never worked with MySQL, but maybe you're forgetting %% on your LIKE clauses. The way it is, it will work like =.
SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like '%antw%' or print_location like '%helm%')
You need parentheses on your second set "OR" of conditions:
query = "SELECT id, date, contactinfo, orderinfo, contents, print_location, order_id, file_size FROM orders where date between " + dateFrom + " and " + dateTill + " and (print_location like 'antw' or print_location like 'helm')";
Otherwise, your statement reads like this:
Get me all this stuff, where date between this date and this date, and print_location like 'antw'...
Or get me all this stuff where print_location like 'helm'.
Since you're using a like, it's probably just freezing while executing your query. It would eventually finish, and you'd have way more results than you were expecting.
Also, because of injection concerns, and data modeling, you should really use a data access object model (DAO). I suggest researching it!

DateTime.Now to mysql datetime

i got problem with a query, got something like this
command.CommandText = "SELECT " +
"COUNT(a.`id`) " +
"FROM " +
"`messageaccess` a " +
"WHERE " +
"a.`Users_LOGIN` = '" + Settings.UserLogin + "' " +
"AND a.`Status` = '" + Enums.MessageStatus.New + "' " +
"AND a.`FOLDER` = '" + Enums.MessageFolder.INBOX + "'" +
"AND a.`ShowAlert` = '" + Enums.YesNo.No + "'" +
"AND a.`Postponed` <= " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "";
but sql throws me exception
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 '14:40:37' at line 1
tried diffrent combinantions but nothing works :(
The simple answer is not to embed values directly into the SQL to start with.
Use a parameterized SQL statement, specify the parameter value as DateTime.Now, and all will be well:
Your SQL will be easier to read (as it'll just be the code, not the data)
You won't need to worry about formatting of things like numbers and dates
You won't be vulnerable to SQL injection attacks
You forgot the quotation marks around the date/time thing.
try using this line instead:
"AND a.`Postponed` <= NOW()"
and it should work with the native MySql function for the current time.
Have a look at named parameterized queries. They take care of these formatting issues for you.
You shouldn't build your query appending strings. This is not very safe (sql injection) and you're not taking advantage of the ADO .NET capabilities to set the correct format according the parameter type.
You should use parametrized queries.

Compare date from database using parameters

string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE (users.ID= " + a.ToString() + ") AND (obroki_save.datum= #datum)";
using (OleDbCommand cmd = new OleDbCommand(queryString,database))
{
DateTime datum = DateTime.Today;
cmd.Parameters.AddWithValue("#datum", datum);
}
loadDataGrid2(queryString);
I tried now with parameters. But i don't really know how to do it correctly. I tried like this, but the parameter datum doesn't get any value(according to c#).
please try this :
database = new OleDbConnection(connectionString);
database.Open();
date = DateTime.Now.ToShortDateString();
string queryString = "SELECT SUM(skupaj_kalorij)as Skupaj_Kalorij "
+ "FROM (obroki_save LEFT JOIN users ON obroki_save.ID_uporabnika=users.ID)"
+ "WHERE users.ID= " + a.ToString()+" AND obroki_save.datum= '" +DateTime.Today.ToShortDateString() + "'";
loadDataGrid2(queryString);
when you use with Date, you must write like this
select * from table where date = '#date'
not like
select * from table where date = #date
While it's usually useful to post the error, I'd hazard a guess and say that you're getting a conversion error with your date.
You should really look at parameterising your queries...
You should read this: http://www.aspnet101.com/2007/03/parameterized-queries-in-asp-net/
And if you can't be bothered reading that, then try changing your 'a' variable to '1; DROP TABLE obroki; --' (but only after you back up your database).
Perhaps you need to write your SQL string in the SQL dialect of the database you're using. In Jet/ACE SQL (what's used by Access), the delimiter for date values is #, so you'd need this:
obroki_save.datum= #" +DateTime.Today.ToShortDateString() + "#"
Of course, some data interface libraries translate these things for you, so that may not be the problem here.

Categories

Resources