How to extract month name of date from MySql query - c#

I have this query which checks for a data repeating four times on the same month 4 or more times. I need to extract the month name or number from this and pass it to string or int.
MySqlConnection connect = new MySqlConnection(MyConString);
string query = "SELECT agentlogin, COUNT(agentlogin), LAST_DAY(`date`) AS Month FROM pending WHERE agentlogin = #login GROUP BY LAST_DAY(`date`) HAVING COUNT(agentlogin) >= 4";
MySqlCommand comm = new MySqlCommand(query, connect);
comm.Parameters.AddWithValue("#login", Label1.Text);
connect.Open();
MySqlDataReader rdr = comm.ExecuteReader();
while (rdr.Read())
{
lblmsg.Text = "GrpM Alert!";
string getMonth = ?;
}
So how can I get this done?
Thanks in advance.

Read the Month field and format it to its name
while (rdr.Read())
{
DateTime date = rdr.GetDateTime("Month");
string getMonth = date.ToString("MMM");
}

The easiest would be:
string getMonth = rdr["Month"].ToString();
And replace LAST_DAY(date) with MONTH(LAST_DAY(date)) or some variation like MONTH(date).
At every step of reading the query with rdr.Read() you can access current row fields through MySqlDataReader object
using it just like array/dictionary: rdr[int i], where i would be index of a field in a row or rdr[string fieldName],
where fieldName is name of a column, which you want to get from particular row.

I think you should be grouping by the month, year, and agent login, then selecting only the year and month. We can use DATE_FORMAT in this case:
SELECT
DATE_FORMAT(date, '%Y-%m') AS yearmonth
FROM pending
WHERE
agentlogin = #login
GROUP BY
agentlogin, -- optional, but included for correctness
DATE_FORMAT(date, '%Y-%m')
HAVING
COUNT(*) >= 4;
Note that this may return more than one month value, if a login happens to match more than one month.
while (rdr.Read())
{
lblmsg.Text = "GrpM Alert!";
int monthNumber = rdr.GetString("yearmonth");
}
The reason for wanting to group by the year and month is that different years could have the same month, and in this case, you probably don't want to report them as being the same thing.

Related

in oracle db format of date 04-DEC-20 while displaying in console shows date like 04-09-2020

i need to fetch last modified date of item in table(oracle db).
in db format of modified date=04-DEC-20
while displaying in console modified date=04-09-2020
c# code to fetch modified date
string connString =DBUtils.GetDBConnection();
OracleConnection conn = new OracleConnection();
conn.ConnectionString = connString;
string sql = "select LASTMODIFIED , name from v_vname where name in('hector')";
OracleCommand cmd = new OracleCommand();
// Set connection for command.
cmd.Connection = conn;
cmd.CommandText = sql;
conn.Open();
using (DbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime);
}
}
}
In Oracle, you can format a date as a string with to_char():
select to_char(lastmodified, 'dd-mm-yyyy') as last_modified, name
from v_vname
where name = 'hector'
Side note: name in ('hector') is simpler phrased name = 'hector'.
It's elegant when you use .ToString("dd-MM-yyyy") in C#
while (reader.Read())
{
int date = reader.GetOrdinal("LASTMODIFIED"); // 0
var LASTmTime = reader.GetValue(0).ToString("dd-MM-yyyy");
Console.WriteLine("modifieddate:" + LASTmTime);
}
DATE data-type values in Oracle are binary values consisting of 7-bytes (which are always century, year-of-century, month, day, hour, minute and second).
What you are seeing when you say the format is DD-MON-RR is the user interface you are using formatting the binary value as something that you, the user, will understand and for SQL/Plus (and SQL Developer and others) this will be based on the NLS_DATE_FORMAT session parameter and the default NLS_DATE_FORMAT value depends on which territory you say you are using when you setup the database.
What you need to do, is the output a string representation of the DATE formatted according to your requirements. You can either do this in SQL and use TO_CHAR to format the string:
SELECT TO_CHAR( LASTMODIFIED, 'DD-MM-YYYY' ) AS last_modified,
name
FROM v_vname
WHERE name = 'hector'
Or could do it in C#:
DateTime LASTmTime = reader.GetValue(0);
Console.WriteLine("modifieddate:" + LASTmTime.toString("dd-MM-yyyy"));

C# Compute Time Using Query

I am developing an Attendance Monitoring System and I need to compute the time difference between OutTime and InTime. The problem is I can't do it because the InTime value is in the Database, I can't seem to parameterize it. My query works with Access' query mode but not with C#. Here's my code for the time out button.
private void savetimeout()
{
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = #" UPDATE TimeinTimeout
SET OutTime = #1 AND HoursWorked = ROUND(([OutTime]-[InTime])*24,2)
WHERE EmployeeID = #2 AND InDate = #3";
command.Parameters.Clear();
command.Parameters.AddWithValue("#1", DateTime.Now.ToLongTimeString());
command.Parameters.AddWithValue("#2", textBox1.Text);
command.Parameters.AddWithValue("#3", DateTime.Now.ToShortDateString());
command.ExecuteNonQuery();
MessageBox.Show("Data Saved!");
this.Hide();
Form1 Mm = new Form1();
Mm.ShowDialog();
}
If I understand correctly, you have a field OutTime that you want to set with the current time and, in the same query, you want to calc the difference between the known value inside the field InTime and the current time.
You could use a query like this
command.CommandText = #"UPDATE TimeinTimeout
SET HoursWorked = #1-[InTime],
OutTime = #2
WHERE EmployeeID = #3 AND InDate = #4";
command.Parameters.Add("#1", OleDbType.Date).Value = DateTime.Now;
command.Parameters.Add("#2", OleDbType.Date).Value = DateTime.Now;
// Is this field really a string?
// If not use the appropriate type and convert the textbox.text
command.Parameters.Add("#3", OleDbType.VarWChar).Value = textBox1.Text;
command.Parameters.Add("#4", OleDbType.Date) = DateTime.Today;
command.ExecuteNonQuery();
Notice that to not confuse the database engine you should specify exactly what your parameters are. Using AddWithValue with DateTime field and passing a string creates a problem because your database engine needs to convert these strings back to datetime values and this conversion could produce unexpected problems. Always specify exactly the type of your parameters.

How to get SQL Server datetime value as it is in 24 hours in C#

I am developing an app in VS2010 c# to fetch a single row data from SQLServer and insert it to MySQL.
I have a table with column name Date_Time containing date and time in 24 hrs. format as shown in below image.
Fetching code is as below.
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}
when I print the value of s_added_date it gives me
My question is why it showing like this and how can I get this time in 24 hrs. format.
Please help to resolve it.
Thanks in advance.
I have a table with column name Date_Time containing date and time in 24 hrs. format
No, you have a table with a column type of DateTime. The values don't inherently have any format - they just happen to be displayed one way in your SQL results viewer, which isn't the same way as .NET formats them by default.
It's very important to understand that the data here is just the date and time - not the format.
To format it in a particular way, cast it to DateTime and then use a ToString overload which allows you to specify the format:
DateTime addedDate = (DateTime) sr["s_added_date"];
string addedDateText = addedDate.ToString("dd-MMM-yyyy HH:mm:ss",
CultureInfo.InvariantCulture);
See the MSDN articles on standard date/time formatting and custom date/time formatting for more information.
However, if the purpose is really just to insert it into MySQL, you shouldn't convert it into a string at all. Just pass the parameter value straight into the appropriate MySQL command as a parameter. Adding string conversions just adds confusion. Wherever possible, keep data in its "natural" type - which in this case is DateTime.
Make following line:
s_added_date = (dr["s_added_date"].ToString());
To
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy HH:mm:ss"));
Your code will be:
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, s_added_date, s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString("dd/MM/yyyy hh:mm:ss"));
s_added_by = (dr["s_added_by"].ToString());
}
If ypu want it as 11-Nov-2013 10:23:25 format:
s_added_date = (dr["s_added_date"].ToString("dd-MMM-yyyy hh:mm:ss"));
Try this
SqlCommand cmd = new SqlCommand("SELECT TOP (1) s_name, s_city, s_address, DATE_FORMAT(s_added_date,'%T'), s_added_by FROM tblAQI ORDER BY s_added_date DESC", SSCon);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
s_name = (dr["s_name"].ToString());
s_city = (dr["s_city"].ToString());
s_address = (dr["s_address"].ToString());
s_added_date = (dr["s_added_date"].ToString());
s_added_by = (dr["s_added_by"].ToString());
}

How to get only the year and month part of a date to compare?

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')

Compare system date with a date field in SQL

I am trying to compare a date record in SQL Server with the system date. In my example the user first register with his name and date of birth which are then stored in the database. The user than logs into the web application using his name only. After logging in, his name is shown on the side where it says "Welcome "player name" using Sessions.
What I am trying to show in addition to his name is a message saying "happy birthday" if his date of birth matches the system date. I have tried working with System.DateTime.Now, but what I think is that it is also comparing the year, and what I really want is the day and the month only. I would really appreciate any suggestion or help.
CODE In Login page:
protected void Button1_Click(object sender, EventArgs e)
{
String name = TextBox1.Text;
String date = System.DateTime.Today.ToShortDateString();
SqlConnection myconn2 = new
SqlConnection(ConfigurationManager.ConnectionStrings["User"].ToString());
SqlCommand cmd2 = new SqlCommand();
SqlDataReader reader;
myconn2.Open();
cmd2 = new SqlCommand("Select D_O_B from User WHERE Username = #username",
myconn2);
cmd2.Parameters.Add("#username", SqlDbType.NVarChar).Value = name;
cmd2.Connection = myconn2
cmd2.ExecuteNonQuery();
reader = cmd2.ExecuteReader();
while (reader.Read().ToString() == date)
{
Session["Birthday"] = "Happy Birthday";
}
}
Note: I using the same reader in the code above this one, but the reader here is with a different connection. Also, reader.Read() is different than reader.HasRows?
Code in Web app Page:
string date = (string)(Session["Birthday"]); // Retrieving the session
Label6.Text = date;
You can replace the code fragment to compare date above with this one
object dobVal = null;
while ((dobVal= reader.Read()) != null)
{
var storedDob = Convert.ToDateTime(dobVal.ToString());
if(storedDob.Month == DateTime.Now.Month &&
storedDob.Day == DateTime.Now.Day)
{
Session["Birthday"] = "Happy Birthday";
}
}
Use ExecuteScalar instead of ExecuteNonQuery() and ExecuteReader(). If D_O_B column in your database is datetime, you can just cast result to DateTime. If D_O_B column is varchar (or something similar), you have to use DateTime.Parse() to convert string to DateTime. Then just compare Day and Month parts of DateTime instances:
DateTime DOB = (DateTime)cmd2.ExecuteScalar();
DateTime Today = DateTime.Now;
if (Today.Month == DOB.Month && Today.Day == DOB.Day)
{
//Happy Birthday
}
Two ways, within in sql you can do a date compare between months and days using the attached page as a reference
sql date compare (bad way for what you want to do)
2) you can cast the incoming string to date time and do a system.datetime.month and system.datetime.day compare against the casted datetime from sql c# better way
I would chose to do way number 2

Categories