Error in accessing the date in asp.net - c#

DateTime startDate = DateTime.ParseExact(txtstart.Text, "yyyyMMdd", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "yyyyMMdd", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between "+
startDate.ToString() + " and "+ endDate.ToString() +" ", con);
It gives error:
String was not recognized as a valid DateTime.When date is entered in
mm/dd/yyyy format

Well yes - you're explicitly specifying that you want to parse it in yyyyMMdd format. I don't see why you'd expect it to work if you've actually specified it in MM/dd/yyyy format. If you want to handle that instead, change your parsing code:
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MM/dd/yyyy",
CultureInfo.InvariantCulture);
However:
If this is parsing user input, you should use DateTime.TryParseExact instead, so you can detect errors in the input in the normal flow instead of using exceptions.
This code is very US-centric; non-US users may well find it confusing. In general you'd either be better off using one of the standard date formats (and the user's culture) or even better, using a date picker control of some form, to avoid the whole text format issue to start with.
Next you're using the values directly in the SQL statement. Don't do that. Always, always, always use parameterized SQL:
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where updateDate between #Start and #End",
con);
adapter.SelectCommand.Parameters.Add("#Start", SqlDbType.Date).Value = startDate;
adapter.SelectCommand.Parameters.Add("#End", SqlDbType.Date).Value = endDate;
(Or create the command first and then pass that to the adapter.)
Using parameterized SQL has three benefits:
It avoids SQL injection attacks
It avoids data conversion issues (which are common with dates)
It keeps your SQL easy to read by separating the code from the data

Access DB Only
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where format( updateDate,'MM/dd/yyyy') between '"+
startDate.ToString("MM/dd/yyyy") + "' and '"+ endDate.Tostring("MM/dd/yyyy") +"' ", con);
Sql Server
DateTime startDate = DateTime.ParseExact(txtstart.Text, "MMddyyyy", null);
DateTime endDate = DateTime.ParseExact(txtend.Text, "MMddyyyy", null);
SqlDataAdapter adapter = new SqlDataAdapter(
"select * from Membership_det where Convert(varchar(15), updateDate,106) between '"+
startDate.ToString(dd MMM yyyy) + "' and '"+ endDate.Tostring(dd MMM yyyy) +"' ", con);

Related

Checking if current date exists in database using c#

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

Error while taking date between two dates

I am trying to get date between two dates but i get error
selection query is
DateTime startdate = Convert.ToDateTime(metroLabel8.Text);
DateTime enddate = Convert.ToDateTime(metroLabel9.Text);
SqlCommand cmd = new SqlCommand("Select [LedId],[LedName] from [Ledger] where Date>='"+startdate+"' and Date<='"+enddate+"'", con);
error is
Please, do not hardcode, use parametrized queries instead
DateTime startdate = Convert.ToDateTime(metroLabel8.Text);
DateTime enddate = Convert.ToDateTime(metroLabel9.Text);
...
// Make sql readable
string sql =
#"Select [LedId],
[LedName]
from [Ledger]
where Date >= #prmStartDate and Date <= #prmEndDate";
// wrap IDisposable (SqlCommand) into using
using (SqlCommand cmd = new SqlCommand(sql, con)) {
cmd.Parameters.Add("#prmStartDate", SqlDbType.DateTime).Value = startDate;
cmd.Parameters.Add("#prmEndDate", SqlDbType.DateTime).Value = endDate;
...
}
Hardcoded queries are
Prone to Sql injection
Brittle (depends on, say, datetime formatting - the gap you fell into)
Slow: there's performance decrease since RDBMS has to parse the query each time it executes it
The best way to handle conversion is to let the provider handle that for you:
DateTime startdate = Convert.ToDateTime(metroLabel8.Text);
DateTime enddate = Convert.ToDateTime(metroLabel9.Text);
SqlCommand cmd = new SqlCommand("Select [LedId],[LedName] from [Ledger] where Date >= #startDate and Date <= #endDate", con);
SqlParameter startParameter = cmd.Parameters.Add("#startDate ",
System.Data.SqlDbType.DateTime);
SqlParameter endParameter = cmd.Parameters.Add("#endDate",
System.Data.SqlDbType.DateTime);
startParameter.Value = startdate;
endParameter.Value = enddate;
cmd.Parameters.Add(startParameter);
cmd.Parameters.Add(endParameter);
Don not concatenate strings when building up your SQL queries, this is prone to SQL injection and is considered a security issue in your code.
Without seeing your inputs, I would suggest you use parameterized SQL in your C# or create a stored procedure to accept DATETIME parameters. You shouldn't use hardcoded SQL queries - in short: they are prone to attack and not optmized in SQL.
A really easy way to do this would be to use the Dapper.NET object mapper.
In SQL, you could do:
CREATE PROCEDURE return_led_for_dates
#startdate DATETIME,
#enddate DATETIME
AS
BEGIN
SELECT
[LedId],
[LedName]
FROM
[Ledger]
WHERE
Date BETWEEN #Startdate AND #Enddate
END
And with Dapper, your C# could then be:
DateTime startdate = Convert.ToDateTime(metroLabel8.Text);
DateTime enddate = Convert.ToDateTime(metroLabel9.Text);
var LED = this.Connection.Query<LED>(
"return_led_for_dates",
new {
StartDate = startdate,
EndDate = enddate
},
commandType: CommandType.StoredProcedure);
You would need an LED class too:
public class LED
{
int LedId {get; set;},
string LedName {get; set;}
}
Finally, this assumes that there is no issue with your text field conversions, you should use DateTime.TryParse. You can then bullet proof your code, and ensure the field is corretly parsed. Like:
DateTime startDate;
DateTime endDate;
if (DateTime.TryParse(Convert.ToDateTime(metroLabel8.Text), out startDate) && DateTime.TryParse(Convert.ToDateTime(metroLabel9.Text), out endDate))
{
// Your data code.
}

C# Generate Query to Compare DateTime with SQL Nvarchar date Column

I tried to get result depending on two dates which the user checked.
I have two datetimepicker controls.
I want the user to chooses the "from" date and "to" date,
then the query get specific result.
leaving_time column type is nvarchar
This is my query:
SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN '"+dateTimePicker1.Checked.ToString()+ "' AND '" + dateTimePicker2.Checked.ToString() + '"
Where is the mistake?
You should write parameterized queries and not using string concatenation for passing the parameters, in order to create a sql command. Using string concatenation makes you code vulnerable to sql injections.
var cmdText = #"SELECT ...
FROM dbo.Hodor_data
WHERE leaving_time BETWEEN #StartDate AND #EndDate";
var sqlCommand = new SqlCommand(cmdText, connection);
sqlCommand.Parameters.AddWithValue("#StartDate", dateTimePicker1.Value);
sqlCommand.Parameters.AddWithValue("#EndDate", dateTimePicker2.Value);
where connection is your sql connection object.
Try to use dateTimePicker1.Text in dateTimePicker1_ValueChanged event where you are using dateTimePicker2.Checked that return true or false not the value of date
Checked is a boolean property, and it is not the date. You need to use the Value Property. It is better to add parameters and explicitly specify the type so that the date format conflict is solved.
Edit: If column type in SQL server is NVARCHAR and of format MM/dd/yyyy, you need to use ONVERT(DATETIME, leaving_time, 101):
conn.Open();
SqlDataAdapter dataAdapter =
new SqlDataAdapter("SELECT name, mil_no, rotba, arrival_time, leaving_time, day, year "
+ "FROM dbo.Hodor_data where CONVERT(DATETIME, leaving_time, 101) "
+ "BETWEEN #p1 AND #p2", conn);
SqlParameter fromDate = new SqlParameter("#p1", SqlDbType.DateTime2);
fromDate.Value = dateTimePicker1.Value;
SqlParameter toDate = new SqlParameter("#p2", SqlDbType.DateTime2);
toDate.Value = dateTimePicker2.Value;
dataAdapter.SelectCommand.Parameters.Add(fromDate);
dataAdapter.SelectCommand.Parameters.Add(toDate);
DataTable dt = new DataTable();
dataAdapter.Fill(dt);
dataGridView1.DataSource = dt;
conn.Close()
You should really consider changing the type of column leaving_time to be a DateTime column. This will make your life easier in querying. I can't really see any advantage of storing these values as text.

Format String for SQL Entry

The user enters the date as MM/DD/YYYY in a string and it needs to be formatted in C#/ASP.NET for insertion into a SQL Server 2008 R2 record. I understand I should convert it to a datetime and parameterize it into the query, but can't find an example of this.
What is the easiest way to do this?
Use DateTime.Parse and in your query add the re turned DateTime as parameter.
var date = DateTime.Parse(theString);
SqlCommand cmd = new SqlCommand("insert into xxx (theDateField) values(#param1)", con);
cmd.Parameters.AddWithValue("param1", date);
//execute your query and do what even you want.
I understand that question is answered but this might be also helpful
DateTime regDate = DateTime.MinValue;
if (txtDate.Text.Trim().Length > 0)
{
string[] ddmmyyyy = txtDate.Text.Trim().Split(new char[] { '-', '/' });
regDate = Convert.ToDateTime(ddmmyyyy[1] + "/" + ddmmyyyy[0] + "/" + ddmmyyyy[2]);
}
Now your date is ready you can insert in database using whatever method you like.
cmd.Parameters.AddWithValue("#RegDate", regDate);
or
SqlParameter paramRegDate = new SqlParameter("#RegDate", SqlDbType.DateTime);
selCmd.Parameters.Add(paramRegDate);

How to get short date format from the datetime object

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");

Categories