Searching database with date - c#

In my windows form, i have one text box where users enters the date in the format 16/02/2013 to search for all the entries on that particular date.
In database i have one column which stores date in this format.16/02/2013 02:47:36 AM.
Can somebody advise me with sql query to extract all the entries from database for that particular date and put it on dataset.
I am using this but it is not working.
public DataSet OrderByDate(string date)
{
// string connString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Users\\Amrit\\Desktop\\Database.accdb ;Persist Security Info=False;";
DataSet dataSet = new DataSet();
OleDbConnection oleConn = new OleDbConnection(connString);
try
{
oleConn.Open();
string sql = "SELECT Customer.[Title] + SPACE(2) + Customer.[Customer's Name] as CustomerName, Customer.[Customer's Ebayname], Customer.[Email Address], Customer.[Phone Number], Customer.[Address 1] + SPACE(2) +Customer.[Address 2] + SPACE(2) + Customer.[City] + SPACE(2) + Customer.[Post Code]+ SPACE(2) + Customer.[Country] as Address, Customer.[Item Purchased], Customer.[Purchased Date], Customer.[Total Price] FROM Customer WHERE [Purchased Date] LIKE '" + "'" + date + "%'";
OleDbDataAdapter dataAdapter = new OleDbDataAdapter(sql, oleConn);
dataAdapter.Fill(dataSet, "Customer");
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
finally
{
oleConn.Close();
}
if (dataSet.Tables.Count <= 0)
return null;
else
return dataSet;
}
In datbase the datetime is stored as Date/Time format.

On the database side, if your datatype is date, you can simply do:
where yourdatefield = #dateIn
If it's a datetime, you do this:
where yourdatefield >= #dateIn
and yourdatefield < the day after #dateIn
Since you are using .net there are a couple of things you need to improve in your application code. First, convert the date string to a DateTime object. Second, convert all the user inputs to parameters.

You may or may not need to enclose the datetime in single quotes in the sql, I dont remember:
DateTime start = DateTime.Parse("16/02/2013").Date;
DateTime end = start.AddDays(1);
string sql = "Select * From Customer WHere PurchasedDate >= {0} and PurchasedDate < {1}";
sql = string.Format(sql, start, end);
Also, this is a quick and dirty method that I wrote up here. It should work, but you REALLY should paramaterize this query.

Passing date values in this way does not work, because default formatted date and time value in .NET is not recognized by your SQL engine.
To pass any data to your query, it is best to always use parameters. Add a parameter to you command string:
string sql = "SELECT * FROM Customer WHERE PurchaseDate = #pdate";
OleDbDataAdapter adapter = new OleDbDataAdapter(sql, connection);
adapter.SelectCommand.Parameters.AddWithValue("pdate", date);
adapter.Fill(dataSet, "Customer");
#pdate in the command text is a parameter. Values for the parameter must be supplied before executing the command, as you see in the example.
You can also use simple string concatenation to fill in your values into your SQL statement, but that's only possible with simple integer or string values, and is generally not recommended because it is subject to SQL injection attack.

Related

C# database compare one Date/Time field from a table with today

To make the story short I have a table inside of which I have a column of type Date/Time. I used MS Acces 2013 to create the database. Now, I need at a certain point in my app to check and delete all the records that are having their date smaller than today. Let's say that conn is my connection to my database. I wrote:
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '" + DateTime.Now + "'";
ExecQuery(delRec);
conn.Close();
If I replace the string with, let's say:
string delRec = "DELETE FROM myTable WHERE anIntColumn < 21";
everything is running just fine. What am I doing wrong? Many thanks.
You could use the built in Now() function:
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < Now()";
ACCESS is not recognizing as a date passed in WHERE clause.
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '#" + DateTime.Now + "#'";
ExecQuery(delRec);
conn.Close();
There may be one more point to check that are you passing same date format in where clause parameter. e.g 'YYYY/MM/DD'
Can you try this one. Hope this will help
Have you tried DateTime.Now.Day method
i.e.
conn.Open();
string delRec = "DELETE FROM myTable WHERE myDateTimeColumn < '" + DateTime.Now.Day + "'";
ExecQuery(delRec);
conn.Close();
Hope it will help you.

C# - Why doesn't time and date save in mysql database?

I have the following code:
private void saveDT()
{
MySqlConnection myConn = new MySqlConnection(Common.myConnection);
myConn.Open();
string sLastLogin = DateTime.UtcNow.ToString("dd.MM.yyyy HH:mm:ss");
MySqlCommand mySqlCmd = new MySqlCommand("UPDATE ha_system.tblaccounts SET lastlogin='" + DateTime.Now.ToString("dd.MM.yyyy HH:mm:ss") + "' WHERE name='" + Common.ActiveUser + "'", myConn);
try
{
mySqlCmd.ExecuteNonQuery();
}
catch (Exception ex)
{
MessageBox.Show("Fehler: " + ex.Message);
}
finally
{
}
}
But time and date is only saved after the second login in the database column "lastlogin".
Why? What can I do to fix this?
beside the other comments about avoiding SQL injection, you do not need to get a DateTime value from .NET into the MySQL server, you can use built in function and have a query like this:
"UPDATE ha_system.tblaccounts SET lastlogin=NOW() WHERE ..."
If you write the datetime literal in a valid format, it should work fine.
dd.mm.yyyy hh:mm:ss is not a valid format for a MySQL datetime literal. It's also ambiguous, at any rate. Try yyyy-mm-dd hh:mm:ss, with the appropriate capitalization of H and M in the right places for the function you're using.
http://dev.mysql.com/doc/refman/5.6/en/date-and-time-literals.html
And, seriously, don't build queries by concatenating strings.

Insert datetime from C# into SQL Server database

when I try to insert datetime value into a SQL Server database I get this error:
Conversion failed when converting date and/or time from character string
Code:
connection.Open();
SqlCommand command = new SqlCommand("insert into table values(#time)", connection);
command.Parameters.AddWithValue("#time", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
Table table has 1 datetime column called time.
Edit:
my table created in msSQL 2012: http://i.imgur.com/TJ3t3y7.png
my real code is:
public void vytvorDotaz(String uzivatel, DateTime cas, String nazev, String dotaz)
{
int id = getMaxID() + 1;
connection.Open();
SqlCommand command = new SqlCommand("insert into otazky values('" + id + "', '" + uzivatel + "', '0','0','0','#cas','" + nazev + "','" + dotaz + "')", connection);
command.Parameters.AddWithValue("#cas", DateTime.Now);
command.ExecuteNonQuery();
connection.Close();
}
The actual problem here is that you're writing the parameter inside quotes:
... ,'0','#cas',' ...
^ ^
This will not use #cas as a parameter, you're actually trying to insert the string "#cas" into that column, not the contents of the parameter #cas.
Remove the quotes and that part should work.
Additionally, don't use string concatenation to build up the SQL, use parameters for everything, save you some headache from SQL injection attacks or quotes or whatnot. This is related to the "id", "uzivatel", "nazev", and "dotav" parameters you're using (method parameters that is).
Looks like you need:
insert into table values(#time)
Without the single character quote.
Try System.Data.SqlTypes.SqlDateTime Also when storing dates please consider storing them as UTC to prevent confusion.

How to Convert date into dd.MM.yyyy format in C# from excel

In excel sheet i have date in format dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). When i'm importing data from excel to SQL Server 2008 i get MM.dd.yyyy but still 16.10.2011 (16 as MM, 10 as dd). That's not correct. I found solution on this: go to SQL Server 2008 -> Security -> logins -> {user properties} -> and change default language for user. With this solution i get in SQL Server 2008 dd.MM.yyyy 16.10.2011 (16 as dd, 10 as MM). Is there any other way to convert date in dd.MM.yyyy format without changing user language?
String sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=c:\\JantarV7Export.xlsx;Extended Properties=Excel 8.0";
OleDbConnection olecon = new OleDbConnection(sConnectionString);
olecon.Open();
OleDbCommand cmd = olecon.CreateCommand();
cmd.CommandText = "SELECT person_id, date_of_hours, number_of_hours FROM [Sheet1$]";
OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
OleDbDataReader odr = cmd.ExecuteReader();
conn.Open();
while (odr.Read())
{
SqlCommand cmd1 = conn.CreateCommand();
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] + "',#date_of_hours,'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
}
cmd1.ExecuteNonQuery();
olecon.Close();
conn.Close();
I think that problem is when i'm inserting into test_data datatable. So i probably should convert dates somehow before inserting. What do you suggest? Thanks. Is there any options like this:
cmd1.CommandText = "INSERT INTO test_data values (newid(),'" + odr[0] +
"',CONVERT(VARCHAR(20),#date_of_hours,104),'" + odr[2] + "')";
cmd1.Parameters.Add("#date_of_hours", SqlDbType.DateTime).Value =odr[1];
(this doesn't work because of CONVERT in insert, but is there some similar solution) or
CONVERT(VARCHAR(20),#date_of_hours,104) AS [DD:MM:YYYY]
UPDATE
In other form i read data through combobox. It shows 1.10.2011, 2.10.2011, .... to 16.10.2011.
da_test_data = new SqlDataAdapter("SELECT test_data_id, date_of_hours, number_of_hours FROM test_data WHERE _person_id= '" + person_id_person + "' ORDER BY date_of_hours", conn);
dt_test_data = new DataTable();
da_test_data.Fill(dt_test_data);
cb_datum.DataSource = dt_test_data.DefaultView;
cb_datum.ValueMember = "test_data_id";
cb_datum.DisplayMember = "date_of_hours";
And combobox for projects:
private void cb_datum_SelectedIndexChanged(object sender, EventArgs e)
{
DataRowView drvProjekt = cb_datum.SelectedItem as DataRowView;
if (drvProjekt != null)
{
string date1 = drvProjekt["date_of_hours"].ToString();
DateTime date2 = new DateTime();
date2 =Convert.ToDateTime(date1);
//DateTime date = DateTime.ParseExact(date1, "MMddyyyy hh:mm:ss", null);
//DateTime date = DateTime.ParseExact(date1, "dd.MM.yyyy", System.Globalization.CultureInfo.CurrentUICulture.DateTimeFormat);
//object obj = DateTime.ParseExact(dddd, "MM/dd/yyyy hh:mm", null);
conn = new SqlConnection(connectionString);
conn.Open();
da_projekt = new SqlDataAdapter("SELECT projekt_id, name_of_projekt, date_of_start, date_of_end FROM projekt WHERE date_of_start < '" + date2 + "' AND date_of_end > '" + date2 + "' ", conn);
dt_projekt = new DataTable();
da_projekt.Fill(dt_projekt);
cb_projekt_id.DataSource = dt_projekt.DefaultView;
cb_projekt_id.ValueMember = "projekt_id";
cb_projekt_id.DisplayMember = "name_of_projekt";
conn.Close();
}
}
When i select 13.10.2011 i get error. Date is recognised as MM.dd.yyyy. I tried everything (all in comments and many more). Yust don't find a solution.
As I mentioned in the comment. your date value is stored as Date in SQL. So when you store date in SQL it will remain date only, and when you retrieve it you will get date object directly. In SQL, it might be displayed as MM.dd.yyyy it doesn't matter.
When you will read this data from SQL, you will get DateTime object, on this if you do .ToString("dd.MM.yyyy", CultureInfo.InvariantCulture) you will get in dd.MM.yyyy format. You can use any format on DateTime object, read more about it on MSDN.
Hope this answers your question.
If possible, just replace "." with "/" in the excel file and format the cell as dd/mmm/yyyy
Excel natively keeps dates as days since some date I do not remember as a floating point value. The important thing is that this matches DateTime.ToOADate().
We read dates from excel files as a floating point value and then use DateTime.ToOADate().
You use CONVERT the wrong way. Database-side, you convert a datetime to a string (varchar), and then you have to rely on build-in type conversions to get a datetime again. You should do it the other way around. If in c# you convert the datetime to a string with a specified format and convert it to a datetime with a matching style database-side nothing can go wrong.
When you use CONVERT the date part should match the style you use (in your case 104). Use this in your sql:
CONVERT(DATETIME, #date_of_hours, 104)
and
cmd1.Parameters.Add("#date_of_hours", SqlDbType.NVarChar).Value =
string.Format("{0:dd.MM.yyyy}", odr[1])

C# Datetimepicker -Date search is not same as return result

I have a problem with my stand alone C#.net application when comes to datetimepicker.
It tooks me weeks and not able to get it solve. I hope you can give me a hand.
I have a [create booking], [Search Booking], and [DB] using ms access.
1) Create booking date using the datetimepicker.
format= short
cmd.CommandText = "insert into booking(cname, bdate, btime, ccontact, sname) Values('" + txt_cname.Text + "','" + **dtp_bdate.Value.Date** + "','" + dtp_btime.Value + "','" + txt_ccontact.Text + "','" + txt_sname.Text + "')";
2) Data store in DB is correct.
Example: 01/10/2011 (it is 1st of October 2011)
3) Search Booking date using the datetimepicker.
format= short
string strSql = String.Format("SELECT * FROM booking WHERE bdate = #{0}#", dtp_search.Value.Date);
When I try to search as in 01/10/2011. It doesn't return the result for me.
But when I try to search as in 10/1/2011, it then appeared the result.
I checked on the DB and confirm the date format is saved as 01/10/2011.
But I don't understand why and how this weird thing happen.
Can any kind man give me a hand?
Truly appreciated in advance.
Thank you,
Gary Yee
Looks like Access allows fixed format dates in sql queries (MM/DD/YYYY). And the date is displayed formatted according to the current culture of the database browser (so you get DD/MM/YYYY). Just use (MM/DD/YYYY) in queries.
"IF" your data is correct, try using parameters instead:
DataTable dt = new DataTable();
using (var cn = new OleDbConnection(strConn))
{
cn.Open();
using (var cmd = new OleDbCommand("SELECT * FROM booking WHERE bdate = #bdate", cn))
{
cmd.Parameters.AddWithValue("#bdate", dtp_bdate.Value.Date);
using (OleDbDataAdapter oda = new OleDbDataAdapter(cmd))
oda.Fill(dt);
}
}
Otherwise, try debugging your statement by trying >= or <= for your "WHERE bdate = #bdate" statement to see if that changes the results.

Categories

Resources