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

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.

Related

Passing DateTime.Now into Access database

I am facing a problem on passing the DateTime.Now into Access database:
oleDBCommand.CommandText =
"INSERT INTO tblData "([PIC], [Sampling Date]) "VALUES (#PIC, #SamplingDate)";
oleDBCommand.Parameters.Add(new OleDbParameter("#PIC", combobox1.Text));
oleDBCommand.Parameters.Add(new OleDbParameter("#SamplingDate", DateTime.Now));
I tried a lot of methods from the internet like using oleDBType.Date, DateTime.Now.ToString(), using AddWithValue..... And none of it is working.
Note 1: Database setting [Sampling Date] = Data Type: Date/Time (Format - Long Time), database was
Note 2: Below code was working but I prefer to using .parameters as it look much more organize and easy to manage.
oleDBCommand.CommandText =
"INSERT INTO tblData ([PIC], [Sampling Date]) " VALUES ('" + combobox1.Text + "', '" + DateTime.Now + "')";
You dont need to pass parameter when specifying current date.
Let the ms access sql query handle it, you need to replace #SamplingDate parameter to Date() for example
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, Date())";
Here is the best explanation Insert today's date
I was struggling with this this week and the accepted answer really did not help me. I found that if I did the assignment of the date+time as an ODBC canonical string (yyyy-mm-dd hh:mi:ss), it worked just fine. So, my C# code looked something like:
InsertCommand.Parameters.Add("#" + column.ColumnName, OleDbType.DBTimeStamp).Value = DateTime.Now.ToString("u");
for the first row and then
InsertCommand.Parameters.Add("#" + column.ColumnName).Value = DateTime.Now.ToString("u")
for the rest.
Try This,
cmd.CommandText = "INSERT INTO tblData ([PIC], [Sampling Date]) VALUES (#PIC, #SamplingDate)";
cmd.Parameters.Add("#PIC",OleDbType.VarChar).Value = combobox1.Text;
cmd.Parameters.Add("#PIC", OleDbType.Date).Value = DateTime.Now;
c# ms-access

"Out-of-range value" error when converting a varchar to datetime

I have this code
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
The problem is whenever it is running in server it is giving error. In Local host or in SQL server management it is working fine.
What the heck is it not working whenever it is in the web
The error is The conversion of a varchar data type to a datetime data
type resulted in an out-of-range value. The statement has been
terminated.
Never concatenate string to form SQL queries, always use parameterized query. For your code you can use SqlParameter, with your command. There instead of Converting DateTime to string and then casting it back DateTime in INSERT query , simply add the value of DateTime object in parameter. This will not only save you from Sql Injection but also resolves issues like the one you are having.
Something like:
using(SqlConnection conn = new SqlConnection("Connectionstring"))
using (SqlCommand cmd = new SqlCommand())
{
string sql = "insert into Usertable ";
sql += "values(#mVendid, #usrname, #usrpass, #datecreation, #createdby)";
cmd.CommandText = sql;
cmd.Parameters.AddWithValue("#mVendid", mVendid);
cmd.Parameters.AddWithValue("#usrname", username);
cmd.Parameters.AddWithValue("#usrpass", userpass);
cmd.Parameters.AddWithValue("#datecreation", Convert.ToDateTime(datecreation));
cmd.Parameters.AddWithValue("#createdby", createdby);
cmd.Connection = conn;
conn.Open();
cmd.ExecuteNonQuery();
}
if datecreation is coming from a DateTime object then add that directly, otherwise you can parse it to DateTime object and let SQL server handle the rest for you.
The problem is that probably you server has different language settings that your machine.
To make sure that converting is working you Convert function. Full tutorial is here: http://www.sqlusa.com/bestpractices/datetimeconversion/
BTW constructing queries like concatenate string is very dangerous way. Instead of this use SqlParamerts. Moreover advantage using this approach is that .NET will do conversion for you.
First of all user parameters (better, clearer and safer!). Second this error happens due to format issues.
datecreation = todaydate.Substring(6, 4) + todaydate.Substring(3, 2) +
todaydate.Substring(0, 2)
string date = DateTime.Parse(datecreation);
string sql = "insert into Usertable values(#mvendid, #username, #usrpass, #date, #createdby)";
var con = new SqlConnection(""); // your connection string
var cmd = new SqlCommand(sql, con);
cmd.Parameters.AddWithValue("#mvendid", mVendid);
...
cmd.Parameters.AddWithValue("#date", date);
First of all its really a bad query and quite hacky, you shouldn't be writing query like this
string sql = "insert into Usertable ";
sql += "values(" + mVendid + ", '" + usrname + "','" + usrpass + "', cast('" +
datecreation + "'as DATETIME),'" + createdby + "')";
*Always use Paramaterised Queries *
Error might be there because you are converting some text to datetime. Possible reasons Datetime not well formed
Dateimte doesn't matches to your server datetime
Try to print out the exact value what its creating
cast('" +
datecreation + "'as DATETIME)
Check the time zone of the server. Likely that it is a different time zone to your local machine. You can avoid the issue by using parameters.
string sql = #"
INSERT INTO Usertable
VALUES (#Parameter1, #Parameter2, #Parameter3, #Parameter4, #Parameter5)";
(using SqlCommand command = new SqlCommand(sql, myConnection))
{
command.Parameters.AddWithValue("#Parameter1", mVendid);
command.Parameters.AddWithValue("#Parameter2", usrname);
command.Parameters.AddWithValue("#Parameter3", usrpass);
command.Parameters.AddWithValue("#Parameter4", todaydate);
command.Parameters.AddWithValue("#Parameter5", createdBy);
command.ExecuteNonQuery();
}

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.

DateTime operator giving strange results

I have two SQL query strings, one of which works and one of which doesn't.
The working one:
string updateLoginTime = "UPDATE DeviceUsers SET lastLogin = '" + dateTime + "' WHERE ID = '" + userID + "'";
This one doesn't:
string updateText = "UPDATE DocumentsRead SET timeRead = '" + dateTime + "' WHERE userID = '" + userID + "' AND fileName = '" + fileOnly +"'";
It throws an error:
The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.
In both queries the dateTime parameter is passed into a web method as a string.
Any ideas why the first one works but the second doesn't?
-EDIT-
The second query is now formatted as follows:
dateTime = DateTime.Now.ToString("dd-MM-yy HH-mm-ss");
using (var conn = new SqlConnection(ConfigurationManager.ConnectionStrings["EndUsersConnectionString"].ConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", dateTime);
cmd.Parameters.AddWithValue("#userId", userID);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
Still getting the same error.
Never do that. NEVER use string concatenations to build SQL queries. ALWAYS use parametrized queries if you don't want to meet Bobby Tables:
using (var conn = new SqlConnection(someConnectionString))
using (var cmd = conn.CreateCommand())
{
conn.Open();
cmd.CommandText = "UPDATE DocumentsRead SET timeRead = #timeRead WHERE userID = #userID AND fileName = #fileName";
cmd.Parameters.AddWithValue("#timeRead", someDateTimeInstance);
cmd.Parameters.AddWithValue("#userId", userId);
cmd.Parameters.AddWithValue("#fileName", fileName);
cmd.ExecuteNonQuery();
}
This way not only that you won't meet with Bobby Tables but your query will work correctly.
The golden rule that should be respected when doing SQL development is not never use the + operator.
Double check your datatypes on the table properties.
DeviceUsers.lastLogin type seems to be correctly set to Date, but perhaps DocumentsRead.timeRead isn't correctly configured.
Concatenating sql query is a bad practice in common so it is better to use parametrized query, however in your case you're possibly working in an environment with different locales so the application server and dbms use different date formats (dd/mm/yyyy and mm/dd/yyyy for example)

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