I have a MySQL database, there's a table which have column Time's Type is Nvachar(50) and its values is kind like this "05/09/2012 20:53:40:843" *(Month-date-year hour:mins:second:msecond)*
Now I want to query to get a record have Time after "10/05/2012 01:00:30 PM".
I had code in C# to converted it to "05/10/2012 13:00:30" before making a query.
My Query :
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
But i got no record. So please tell me how can I can make it return record have time after the time above ???
More Info My C# code :
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
var query = "SELECT * FROM " + tableName + " WHERE capTime > '" + date + "' LIMIT 0, 1";
var cmd = new MySqlCommand(query, connection);
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
I'm so so so so so so sorry. I made a mistake the query must be
SELECT * FROM ABCDFEGH WHERE capTime > '05/10/2012 13:00:30' LIMIT 0, 1
This query is successful return the record i need :)
But soemhow I have mistyped it into
SELECT * FROM ABCDFEGH WHERE capTime > '05-10-2012 13:00:30' LIMIT 0, 1
Sorry again, topic close. But tks for evveryone tried :)
I recommend using the DATETIME datatype instead of NVARCHAR. Store dates in YYYY-MM-DD HH:MM:SS format, which is the native DATETIME format recognized by MySQL.
Also use date literals in the same format.
Two reasons for this recommendation: First, DATETIME takes only 8 bytes, instead of up to 150 bytes which is the potential size of a multibyte 50 character varchar.
Second, the sort order of DATETIME will be the same as the chronological order. So if you create an index on the Time column, your > comparison can benefit from the index. Your query will be much faster as a result.
Use TIMESTAMPDIFF()
Schema
CREATE TABLE ABCDFEGH (`right` varchar(3), `time` datetime);
INSERT INTO ABCDFEGH (`right`, `time`)
VALUES
('Yes', '2012-10-02 13:00:30'),
('No', '2012-10-15 13:00:30');
SQL Code
SELECT * FROM ABCDFEGH
WHERE TIMESTAMPDIFF(MINUTE, time, '2012-10-05 13:00:30') > 0
LIMIT 0, 1
Explanation
TIMESTAMPDIFF() returns datetime_expr2 – datetime_expr1, where datetime_expr1 and datetime_expr2 are date or datetime expressions. One expression may be a date and the other a datetime; a date value is treated as a datetime having the time part '00:00:00' where necessary. The unit for the result (an integer) is given by the unit argument.
Fiddle: http://www.sqlfiddle.com/#!2/244cc/1 datetime
Fiddle: http://www.sqlfiddle.com/#!2/063b3/1 varchar(50)
PS1: Time may be a reserved word. Please avoid using it. Else use it with backticks (`).
PS2: The format of time is YYYY-MM-DD not the reverse.
First, why did you save the dates as NVARCHAR? If you are still able to change it to DATETIME datatype and all of the records on it, much better.
But if not, you can use STR_TO_DATE.
SELECT *
FROM tableName
WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') >
STR_TO_DATE('05/10/2012 13:00:30', '%c/%d/%Y %H:%i:%s')
See SQLFiddle Demo
SOURCES
STR_TO_DATE
DATE Formats
UPDATE 1
and your query is vulnerable with SQL Injection. To avoid from it
Parameterized your query
code snippet,
string tableName = "ABCDFEGH";
string date = "05/10/2012 13:00:30";
String query = "SELECT * FROM " + tableName + " WHERE STR_TO_DATE(`capTime`, '%m/%d/%Y %H:%i:%s:%x') > STR_TO_DATE(#dateHere, '%c/%d/%Y %H:%i:%s')";
using (MySqlConnection connection = new MySqlConnection("connectionStringHere"))
{
using (MySqlCommand command = new MySqlCommand())
{
command.Connection = connection;
command.CommandType = CommandType.Text;
command.CommandText = query;
command.Parameters.AddwithValue("#dateHere",date)
MySqlDataReader dataReader = null;
try
{
dataReader = cmd.ExecuteReader();
}
catch(MySqlException e)
{
// do something here
// don't suppress the error
}
}
}
Related
I am building a query string like this.
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
Hwowever, when it executes
while (dataReader.Read())
I am seeing Dates well before the howFarBack ????
public List<OHLC> Select(string table, System.DateTime howFarBack)
{
string query = "SELECT * FROM " + table + " where DATE(Date) > " + howFarBack.ToString("yyyy-MM-dd");
//Create a list to store the result
var list = new List<OHLC>();
//Open connection
if (OpenConnection() == true)
{
//Create Command
MySqlCommand cmd = new MySqlCommand(query, connection);
//Create a data reader and Execute the command
MySqlDataReader dataReader = cmd.ExecuteReader();
//Read the data and store them in the list
while (dataReader.Read())
{
var ohlc = new OHLC();
ohlc.Date = (System.DateTime)dataReader[0];
ohlc.Open = Math.Round((double)dataReader[1], 2);
When in doubt, try to debug by examining the resulting SQL query, not the C# code that formats the SQL query.
I would guess that your query lacks single-quote delimiters around the date literal. So it is ultimately a query like:
SELECT * FROM MyTable where DATE(Date) > 2021-11-02
But 2021-11-02 isn't a date, it's an arithmetic expression that evaluates to an integer: 2021 minus 11 minus 2 = 2008. This will certainly match a lot of dates you didn't intend it to.
You could solve this by ensuring that the right type of quotes are around your date literal (it's actually a string literal that is interpreted as a date when compared to a date).
SELECT * FROM MyTable where DATE(Date) > '2021-11-02'
But it's far better to use query parameters, as mentioned in the comment above.
SELECT * FROM MyTable where DATE(Date) > #howFarBack
Then you don't need quotes. In fact you must not use quotes around the parameter placeholder.
See Parameterized Query for MySQL with C# or many other references for using parameters in SQL statements in C#.
Also remember that parameters can only be used in place of a single literal value. You can't use parameters for table or column identifiers, or a list of values, or SQL keywords, etc.
I am trying to get a list of orders from my access database that were ordered between 2 dates.
this is my query:
"SELECT * FROM Orders WHERE OrderDate >= '#" + DateTime.Parse(txtDate.Text) + "#' AND OrderDate <= '#" + DateTime.Parse(txtEndDate.Text) + "#'";
the 2 textboxes recieve the dates directly from 2 ajax calendar extenders. i have already made sure that the first date is before the second, and i had made sure that the data inserted to the database was also inserted like '#"+date+"#', but i "still data type mismatch in query expression".
can anyone try and identify a problem with my query?
Assuming you have data like this:
var txtDate = new { Text = "2020-08-01" };
var txtEndDate = new { Text = "2020-08-01" };
your query might look like this:
var fromDate = DateTime.ParseExact(txtDate.Text, "yyyy-MM-dd",
CultureInfo.InvariantCulture).ToString("yyyMMdd");
var toDate = DateTime.ParseExact(txtEndDate.Text, "yyyy-MM-dd",
CultureInfo.InvariantCulture).ToString("yyyMMdd");
var query =
$"SELECT * FROM Orders WHERE OrderDate>='{fromDate}' AND OrderDate<='{toDate}'";
or the last part can be:
var query =
$"SELECT * FROM Orders WHERE OrderDate BETWEEN '{fromDate}' AND '{toDate}'";
It is the octothorpes that are delimiters for date expressions, not single quotes. And the formatted text expression for a date value should be forced. Thus:
"SELECT * FROM Orders WHERE OrderDate >= #" + DateTime.Parse(txtDate.Text).ToString("yyyy'/'MM'/'dd") + "# AND OrderDate <= #" + DateTime.Parse(txtEndDate.Text).ToString("yyyy'/'MM'/'dd") + "#";
That said, look up how to run queries with parameters. It takes a few more code lines but is much easier to debug and get right.
You should use a parameterized query for both security and for type safety
Access database queries use ? as a placeholder for the parameters you pass.
OleDbCommand command = new OleDbCommand();
// I assume you have an oledb connection object and it is in open state
command.Connection = myConnection;
command.CommandText = "SELECT * FROM Orders WHERE OrderDate >= ? AND OrderDate <= ?";
// Please note that the name of the parameters are redundant and not used
command.Parameters.AddWithValue("StartDate", DateTime.Parse(txtDate.Text));
command.Parameters.AddWithValue("EndDate", DateTime.Parse(txtEndDate.Text));
// You can also use your data adatper. This is just an example
command.ExecuteReader();
I have a table which I want to insert data in it only once in a day
and to implement that I want to check if current date already exists in
the database by writing these lines
DateTime date = DateTime.Now;
MySqlCommand cmd = new MySqlCommand("SELECT * FROM `attendances` WHERE
`lecture_id` = '" + lecture_id + "' " +
" AND `date` = '"+date.ToShortDateString()+"' ",con);
MySqlDataReader reader = cmd.ExecuteReader();
reader.Read();
if (reader.HasRows)
MessageBox.Show("you can't insert");
else MessageBox.Show("you can insert");
The date is inserted to the database in this format xxxx-xx-xx although using the same method for inserting, and date.ToShortDateString() returns the date in this format
xxxx/x/x .
I checked inserting the date manually in the correct format but that also didn't work, I also tried using the DATE function in sql but that didn't work either.
Just apply format string date = DateTime.Now.ToString("yyyy-MM-dd")
And do not call ToShortDateString() in your SQL query
You also should use SqlParameter as your code is vulnerable for SQL injection attack.
You could also avoid using .NET's DateTime and use MySql's NOW() or UTC_DATE() instead within your query, which may be better; if the region of your code and db reside in different timezones.
i.e.
[...] " AND `date` = DATE(NOW()) ",con);
In my application I want to count the number of records with the same current year and month. So my logic is to compare the current Year and Month to the date_needed column in my table.
Here's how I did it:
using (MySqlConnection con = new MySqlConnection(serverstring))
{
con.Open();
string query = "SELECT * FROM tblOrder WHERE date_needed=#dateTimeNow";
using (MySqlCommand cmd = new MySqlCommand(query, con))
{
cmd.Parameters.AddWithValue("#dateTimeNow", DateTime.Now.ToString("yyyy-MM")); using (MySqlDataReader dr = cmd.ExecuteReader())
{
int count = 0;
while (dr.Read())
{
count++;
}
MessageBox.Show(count.ToString());
}
}
}
I know that it doesn't work because in my messagebox it shows zero instead of one record. What do you think is the problem?
You should supply a complete date (as a DateTime, without formatting it - text conversions are almost always a bad idea when sending parameter values to a database) and use the MySQL date/time functions to compare the values.
For example:
string query = #"SELECT * FROM tblOrder
WHERE MONTH(date_needed) = MONTH(#dateTimeNow)
AND YEAR(date_needed) = YEAR(#dateTimeNow)";
Alternatively, you could pass the month and year as separate parameters:
string query = #"SELECT * FROM tblOrder
WHERE MONTH(date_needed) = #month
AND YEAR(date_needed) = #year";
Or - possibly more performantly - you could give start and end points:
string query = #"SELECT * FROM tblOrder
WHERE date_needed >= #start AND date_needed < #end";
Here you'd set #start to the start of this month, and #end to the start of the next month. You could work those out as:
// Consider using UtcNow.Date instead. Basically, think about time zones.
DateTime today = DateTime.Today;
DateTime start = new DateTime(today.Year, today.Month, 1);
DateTime end = start.AddMonths(1);
If you wanna get Count of rows in sql use
But Need to pass Complete date value in #dateTimeNow
SELECT Count(*) FROM tblOrder WHERE MONTH(date_column)= MONTH(#dateTimeNow) and YEAR(date_column) = YEAR(#dateTimeNow)
If you want to do it all on the MySQL end, try this:
SELECT *
FROM tblOrder
WHERE EXTRACT(YEAR_MONTH FROM date_needed) = EXTRACT(YEAR_MONTH FROM CURRENT_DATE)
To make it fit your #dateTimeNow parameter, which is formatted as yyyy-MM (in .NET this means the year with century, followed by a dash, followed by the month as two digits), do this:
SELECT *
FROM tblOrder
WHERE #dateTimeNow = DATE_FORMAT(date_needed, '%Y-%m')
I have a query which fetches the information from sql server on datematch.
I have searched a lot about SQL Server date string, I just want to match with the date and get the data from database. Also I am using SQL Server 2005, I want to fetch the date and take the time out of it?
Can anybody help me in that... I am new to C#
Here is my query.
return "select Timein, Timeout from Attendance where E_ID = " + E_ID + " and Date = " + DateTime.Now.ToShortDateString();
use the sql server CONVERT function to convert the input date param to time
Change your query to accommodate any one of the below CONVERT function
SQL query to convert Time format into hh:mm:ss:
select convert(varchar, <<dateparam>>, 108)
SQL query to convert Time format into hh:mi:ss:mmm(24h):
select convert(varchar, <<dateparam>>, 114)
You should always use parameters when querying a database - whether or not SQL injection is possible, it's just plain good practice to use parameters, and it solves some of the thorny how many quotes and which kind do I need here to make it a valid SQL statement questions, too.
So try something like:
string sqlStmt = "SELECT Timein, Timeout FROM dbo.Attendance " +
"WHERE E_ID = #ID AND Date = #Date";
using(SqlConnection conn = new SqlConnection("your-connection-string-here"))
using(SqlCommand cmd = new SqlCommand(sqlStmt, conn))
{
// set up parameters
cmd.Parameters.Add("#ID", SqlDbType.Int).Value = E_ID;
cmd.Parameters.Add("#Date", SqlDbType.DateTime).Value = DateTime.Now.Date;
// open connection, read data, close connection
conn.Open();
using(SqlDataReader rdr = cmd.ExecuteReader())
{
while(rdr.Read())
{
// read your data
}
rdr.Close();
}
conn.Close();
}