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!
Related
hey guys when i get data from database my timeStamp is as follow:
timeStamp='2021-02-04 13:01:46.96'
my database call:
NpgsqlDataAdapter adapt = new NpgsqlDataAdapter(#"SELECT * from logs.func_event_log(
'" + id + #"',
'" + myDateFrom + #" 00:00:00' , '" + myDateTo + #" 23:59:59.999'
,'FULLEVENTLOG'
)
res (m_time_stamp timestamp without time zone, m_event_log_description text,
m_user_description varchar, m_event_type_description varchar,
m_wind_speed real, m_rpm real , m_power real,
m_event_type_id int, m_event_number varchar) ", cn);
when I fill the dataset
var data = (from t in ds.AsEnumerable()
select new EventEntryForAllTurbines
{
Timestamp = (DateTime)t["m_time_stamp"],
Description = (string)t["m_event_log_description"],
WindSpeed = (float)t["m_wind_speed"],
}).OrderBy(s=>s.Timestamp);
in my dataset, I see my milliseconds are removed in TimeStamp, my timestamp is DateTime type, how can I keep my milliseconds?
here is the screenshot of my breakpoint and values its shown
here is the screenshot of my DB
I have a class to convert time to send to view
result.Add("DateTime", eventEntry.Timestamp.ToString
(Culture.GetCulture().DateTimeFormat.ShortDatePattern)
+ " " + eventEntry.Timestamp.ToString(Culture.GetCulture()
.DateTimeFormat.LongTimePattern));
First, please make absolutely sure the milliseconds are truly missing. Look what happens when I point to a datetime variable:
The tooltip looks like no milliseconds, but the locals window clearly shows that they're there, as does TimeOfDay etc
This is my code:
string query = "SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = " + jobId + ".00";
SqlDataReader reader = new SqlCommand(query, sqlConn).ExecuteReader();
This is my data:
I want to fetch multiple rows with the exact JOBBNR, but this returns nothing.
EDIT:
The query was working, it was just me being stupid and not searching in the right table. Sorry for wasting anyones time trying to help.
Include the jobId in single quotes. Modify your query to following:
"SELECT TEKN,KOMMENTAR FROM dbo.JOBBTEKN WHERE JOBBNR = '" + jobId + ".00'"
Observe the single quote around jobId.
Looking at the comments, I suspect the datatype of JOBBNR is float; NOT decimel. float datatype internally contains multiple precision, so when you try to match them in WHERE = clause, you may not get result due to mismatched precision.
There are multiple ways to handle this problem. Try something like following:
WHERE JOBBNR BETWEEN 1200.00 AND 1200.01
OR
"WHERE JOBBNR BETWEEN '" + jobId + ".00' AND '" + jobId + ".01'"
I have a rent_date and return_date column in rental table and the data-type is Date. I have created two different strings for them. rentDate is the current date and returnDate is the output of adding the days that the product is rented for, from the current date. I tried to convert the strings using to_date but its showing errors. I have tried it with the data-type varchar2(30). Worked fine. But had to modify to Date because I want a late return date too. Can anyone tell me what is wrong with this query?
DateTime dt = System.DateTime.Now;
string rentDate = dt.ToString();
// this is added to the current date of the user input and showed in the form
string returnDate = label66.Text;
string Query = "Insert into rental ( pr_ID, cid, rent_date, Return_date, status, receipt_no) values ( '" + comboBox5.Text + "' , '" + comboBox4.Text + "', (to_date('" + rentDate + "','dd/mm/yyyy')), (to_date('" + returnDate + "','dd/mm/yyyy')), '" + Status + "', '" + txt_recpt.Text + "') ";
What error are you getting?
I agree with the "Soner" that they should not be text values. However, based on your existing code, you may be getting a format error.
What format is the string value of "rentDate" and "returnDate" in? It needs to be the same as what you've specified in the INSERT query, which is "dd/mm/yyyy". If it's not, an error will be thrown.
The second parameter of the TO_DATE function is the format of the input variable.
Unless you're getting a different error?
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;
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.