OleDbConnection con = new OleDbConnection(#constring);
con.Open();
string cmdstring = "UPDATE table SET date=" + DateTime.Parse(datetxt.Text) +" WHERE id ="+id;
OleDbCommand cmd = new OleDbCommand(cmdstring,con);
cmd.ExecuteNonQuery();
con.Close();
I want to update date column which is stored in access database. But it gives me syntax error(missing operator) in query expression '03.03.2016 00:00:00'
In access date column type is Date/Time.
Try with :
string cmdstring = "UPDATE table SET date='" + DateTime.Parse(datetxt.Text).ToString("dd/MM/yyy") +"' WHERE id ="+id;
Apparently it seems a problem in the date format . The solution indicated by Beldi Anouar should funcionarte .
Good luck
Related
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.
I Have a table with 3 columns, when an alarm goes off, I want the time of that alarm to be stored in the 2nd column of the table(AlarmActivated). Then if that alarm is turned off, it stores that time in the same row of the table but in column 3. This is my code:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString());
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.ExecuteReader();
Con.Close();
This is executed when a value goes to 0.
ExecuteReader returns some data. Since you wanna insert, you need to use ExecuteNonQuery instead.
And do not store your DateTime values as a string. Change your column type to datetime2 and pass your DateTime.Now value directly to your parameterized query. Please read Bad habits to kick : choosing the wrong data type
Also using DateTime.Now can be ambigious. Read Matt's article The case against DateTime.Now
Use using statement to dispose your connection and command automatically instead of calling Close method manually.
Since you insert only one column, other two columns will be null or their default value.
string ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30"
using(var Con = new SqlConnection(ConStr))
using(var Command = Con.CreateCommand())
{
Command.CommandText = "INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarm)";
Command.Parameters.Add("#alarm", SqlDbType.DateTime2).Value = DateTime.Now;
Con.Open();
Command.ExecuteNonQuery();
}
The problem is in
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES" + (DateTime.Now.ToString())
It has to be
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (" + DateTime.Now.ToString() + ")";
wrong function is used, use this function: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx ExecuteNonQuery
First, your string for your insert is badly formed. You need to put the parentheses inside quotes:
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES('" + DateTime.Now.ToString() +"')";
Secondly, you need to use parameterized queries instead, because building your SQL like this is a bad habit to get into and can lead to SQL injection breaches:
String ConStr = "Data Source=(LocalDB)\\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\\PatientHealthMonitor.mdf;Integrated Security=True;Connect Timeout=30";
String Query = " INSERT INTO AlarmResponse (AlarmActivated) VALUES (#alarmTime)";
SqlConnection Con = new SqlConnection(ConStr);
SqlCommand Command = new SqlCommand(Query, Con);
Con.Open();
Command.Parameters.AddWithValue("#alarmTime", DateTime.Now);
Command.ExecuteNonQuery();
Con.Close();
Finally, only the column AlarmActivated will be set with a value. The other two columns will be populated by their default value. If you want the other two columns to have a value other than their default, you need to specify them and provide a value.
You can create 2 stored procedures in SQL, one will insert row and return ##SCOPE_IDENTITY (you can store it in list<>), which you will use as a param for updating procedure.
Try to avoid using SQL statemensts in code, to prevent code injection.
I have this sql statement which references a column in the datagrid, ordName
string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName=" + dto.Rows[i]["ordName"].ToString();
but I get an error message as below
Conversion failed when converting the nvarchar value '021-01072015' to data type int.
I thought that .ToString() would overcome this
Please use a parametrized query
string qryUpdate ="UPDATE Orders SET show=1 WHERE show=0 AND ordName= #ordName ";
using (SqlConnection connection = new SqlConnection(connectionString))
{
SqlCommand command = new SqlCommand(qryUpdate, connection);
command.Parameters.AddWithValue("#ordName", dto.Rows[i]["ordName"].ToString());
}
string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName='#orderName'";
//your command object
cmd.Parameters.AddWithValue("#orderName", dto.Rows[i]["ordName"].ToString());
string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND
ordName= '" + dto.Rows[i]["ordName"].ToString() + "'";
now the update query will be
UPDATE Orders SET show=1 WHERE show=0 AND
ordName= '021-01072015'
string qryUpdate = "UPDATE Orders SET show=1 WHERE show=0 AND ordName='" + dto.Rows[i]["ordName"].ToString()+"'";
Please try this.
var qryUpdate =string.Format("UPDATE Orders SET show={0} WHERE show={1} AND ordName='{2}' ",1,0 ,dto.Rows[i]["ordName"].ToString());
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.
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)