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
Related
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"));
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.
I am capturing the time in the text box (by using AJAX calender extender)
the time in the string is 12/10/2013, but when I assign the string to a datetime object it is converted into 12/10/2013 12:00:00 AM.
I want to use the date to filter the records in the database using the query below. Please help
string date1 = txtDate1.Text;
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy",
System.Globalization.CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName,Story.StoryId,COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=" + date1 + "
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC ;";
It's generally not a good idea to pass dates as strings in your queries because you will most likely run into formatting issues - leave it up to the Framework you are using decide on what the best format is.
In your circumstances, you can do this by using SqlParameters e.g.
DateTime date = DateTime.ParseExact(txtDate1.Text, "MM/dd/yyyy", CultureInfo.InvariantCulture);
string strQuery = "SELECT Story.UserName, Story.StoryId, COUNT(Likes.StoryID) AS NumberOfOrders
FROM Likes LEFT JOIN Story ON Likes.StoryId=Story.StoryId and liked=#dateTime
GROUP BY Story.StoryId,Story.UserName order by NumberOfOrders DESC";
using (SqlConnection connection = new SqlConnection("..."))
{
using (SqlCommand cmd = new SqlCommand(strQuery, connection))
{
cmd.Parameters.AddWithValue("#dateTime", date);
connection.Open();
SqlDataReader reader = cmd.ExecuteReader();
...
}
}
Another important reason to use parameters when writing raw SQL is to ensure your user input is correctly sanatized and safe to pass to the DB. Failure to do this can leave you open to various exploitations such as SQL Injection.
Instead of DateTime object you can use Date object.
DateTime is an integer interpreted to represent both parts of DateTime (ie: date and time). You will always have both date and time in DateTime.
ex:
DateTime.Now.ToString("MM/dd/yyyy");
I'm trying to enter data into my SQL Server 2008 using data from a form. I am using a DateTimePicker to select dates from a form and enters this data to the db, however when I try to run the form I'm getting the following error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
The statement has been terminated
This is the code for my form below:
private void btnAddBooking_Click(object sender, EventArgs e)
{
DateTime requested = dtpRequested.Value;
DateTime pickup = dtpPickup.Value;
DateTime estDropoff = dtpEstimatedDrop.Value;
SAF.AddNewBooking(requested, pickup, estDropoff, selectedStatus.StatusId, selectedRate.RateId);
dtpRequested.CustomFormat = " ";
dtpPickup.CustomFormat = " ";
dtpEstimatedDrop.CustomFormat = " ";
cbStatus.SelectedIndex = 0;
cbRateOfPayment.SelectedIndex = 0;
MessageBox.Show("Booking Created");
tabControl2.SelectTab(2);
}
Here is code in the facade where I store the method:
public void AddNewBooking(DateTime requestedD, DateTime pickupD, DateTime estDropOff, int statusId, int rateId)
{
dao.AddNewBooking(requestedD, pickupD, estDropOff, statusId, rateId);
}//end CreateBooking
and this is the INSERT statement code in my DAO:
sql = "INSERT INTO [Transaction] (TransactionId, RequestedDateOfPickup, ActualDateOfPickup, EstimatedDropOffDate, StatusId, RateId)";
sql += String.Format("VALUES('{0}', '{1}', '{2}', '{3}', {4}, {5})", transactionId, requestedD, pickupD, estDropOff, statusId, rateId);
cn = new SqlConnection(Properties.Settings.Default.UKRENTALSConnectionString);
cmd = new SqlCommand(sql, cn);
cn.Open();
cmd.ExecuteNonQuery();
Probably something to do with the regional settings of the machine that this is being run on, and the date format that is being ultimately passed into your insert statement being something along the lines of:
27/09/2012 4:17:42 PM
(being the current date here in Australia as I write this).
SQL Server may be trying to cast that into whatever date format it's using, and can't (e.g. thinks the first parameter is the month, but 27 is greater than 12).
Try formatting the dates in YYYY-MM-DD format:
2012-09-27
Or better yet, use parameters instead, as you have an SQL Injection vulnerability there.
my question looks simple: in my client/server application I want to record a specific date provided by the client.
The problem is that I don't know the regional settings of the client, and I don't know the regional settings of the SQL Server.
How can the client application provide a date in whatever format (last login of a specific user) and store it in a SQL Server table that might be installed with a different regional settings (french, english, italian, german, etc...).
Simple: don't use strings. Use a parameter that is typed as a datetime; can be as simple as:
DateTime when = ...
using(var cmd = conn.CreateCommand()) {
cmd.CommandText = "... #when ...";
cmd.Parameters.AddWithValue("when", when);
cmd.ExecuteNotQuery();
}
or with "dapper":
conn.Execute("... #when ...", new { when });
Dates/times are actually just numbers. It is only when you write/parse it as a string that formatting is an issue.
Just store everything in UTC date in sqlserver. And while retrieving the date convert the utc date to the timezone of the user. I hope users timezone is maintained in your database.
You will need a timezone table and a conversion function that will convert the UTC time to the users local time.
to insert a date in SQL use a string in the form 'YYYYMMDD'
what comes from the client-side you sould know what is it
You should use Parameters, but you also can format date to ISO format by date.ToString("s")
Use datetime format, and store dates as UTC time.
You'll probably also be interested in datetimeoffset.
Validation part
DateTime dt;
string YourDate = "Your Date";
if (DateTime.TryParse(YourDate, out dt))
{
//Your Code
}
Stored Procedure Record Insertion/Retrieval
using (System.Data.SqlClient.SqlConnection con = new SqlConnection("YourConnection string"))
{
con.Open();
SqlCommand cmd = new SqlCommand();
string expression = "Date Parameter value";
DateTime dt;
if (DateTime.TryParse(expression, out dt))
{
//Your Code
}
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandText = "Your Stored Procedure";
cmd.Parameters.Add("Your Parameter Name", SqlDbType.VarChar).Value = expression;
cmd.Connection = con;
using (IDataReader dr = cmd.ExecuteReader())
{
if (dr.Read())
{
}
}
}
While storing the data in Sql Server Keep the data format consistent and synchronized with the data format while retrieving....