简体   繁体   中英

c# Access DateTime UPDATE via DateTime.Parse

OleDbConnection con = new OleDbConnection(constring)
con.Open()
cmdstring = "UPDATE table SET date="+DateTime.Parse(txtdate.Text).ToString("dd/MM/yyyy") + " WHERE id = 1"
OleDbCommand cmd = new OleDbCommand(cmdstring,con)
cmd.ExecuteNonQuery()
con.Close()

When I try to update a table using this code in one of my forms it is done perfectly. But at the another form I'm using same code to update same table and same column, but I'm getting a confusing error. Syntax error(missing operator)

Example: Date at txtbox: 17.1.1987

Date at the error: 17.1.198

DateTime.Parse is okay. I tried what it is returning. It returns 4 digit year. But what is happening while updating access db?

Regards...

Always use parametrized queries. Especially when you deal with dates in Access you can run into so much trouble.

    DateTime dt;
    bool canParse = DateTime.TryParseExact(txtdate.Text,
                                      "dd/MM/yyyy",CultureInfo.InvariantCulture, 
                                      DateTimeStyles.None, 
                                      out dt);
    if(canParse)
    {
         string sQuery = "UPDATE table SET date = @pdate WHERE ID = @pid";
         OleDbCommand updateCmd = new OleDbCommand(sQuery, Conn);
         updateCmd.Parameters.Add("@pdate", OleDbType.Date).Value = dt;
         updateCmd.Parameters.Add("@pid", OleDbType.Integer).Value = 1; 
         int rowsAffected = updateCmd.ExecuteNonQuery();
         /* Use the result from operation for some notification */
    }
cmdstring = "UPDATE table SET date='"+DateTime.Parse(txtdate.Text).ToString("dd/MM/yyyy") + "' WHERE id = 1"

您需要在日期值前后使用单引号。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM