1

I'm trying to update a table element of type timestamp called dtprint with the current time (the original value is NULL). The code that I am using is as follows:

MySqlConnection con = new MySqlConnection("Connection_String");
con.Open();
MySqlCommand _cmd = con.CreateCommand();

string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");

_cmd.CommandText = "UPDATE requests SET dtprint = " + dt + " WHERE idPerson = " + _personID[index];

_cmd.ExecuteNonQuery();

con.Close();

The exception I keep getting is: Additional information: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '14:03:23 WHERE idPerson = 45' at line 1.

The only thing I can think of is that the Database isn't recognizing the time as a timestamp, any help is greatly appreciated.

4
  • What are the types of dtprint and idPerson columns? And you should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks. If your dtprint is a timestamp, you should add it a DateTime, not string. Commented Oct 29, 2014 at 18:08
  • dtprint is of type timestamp, and idPerson is of type int Commented Oct 29, 2014 at 18:09
  • 5
    put single quotes around your date string. '" + dt + "' Commented Oct 29, 2014 at 18:09
  • do you have access to convert the UPDATE command to a stored procedure..? if so do that..also I would recommend converting the UPDATE statement to utilize Parameterized query and wrap the _cmd.ExecuteNonQuery(); around a try{}catch(SqlException sqlEx{show the sqlEx.Message here} so that you can capture the SQLException Commented Oct 29, 2014 at 18:15

1 Answer 1

2

Since dt is a string and your dtprint is timestamp, you need to use single quotes when you try to insert it. Like;

"UPDATE requests SET dtprint = '" + dt + "' WHERE

But don't use this way.

You should always use parameterized queries. This kind of string concatenations are open for SQL Injection attacks.

Also use using statement to dispose your database connections and objects.

using(MySqlConnection con = new MySqlConnection(ConnectionString))
using(MySqlCommand _cmd = con.CreateCommand())
{
    string dt = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss");
    _cmd.CommandText = @"UPDATE requests SET dtprint = @dtprint
                         WHERE idPerson = @id";
    _cmd.Parameters.Add("@dtprint", MySqlType.TimeStamp).Value = dt; 
    _cmd.Parameters.Add("@id", MySqlType.Int).Value = _personID[index];
     con.Open();
    _cmd.ExecuteNonQuery();      
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.