Search code examples
c#ms-accessoledb

UPDATE query not working with date field


string date= DateTime.Now.ToString("d.M.yyyy",System.Globalization.DateTimeFormatInfo.InvariantInfo);

String MyString = @"UPDATE cas SET Odhod= '" + label1.Text + "' 
WHERE sifra = " + textBox1.Text + " and Datum = "+date+"";

When I do this update without Datum (German for "date") it works, but with Datum it doesn't work. I'm connected to an Accesss database, and the type of the table field Datum is Date/Time.

Here is the program: https://www.dropbox.com/s/hx4zduvul8mh2uy/8.4.zip
Pictre of problem: http://img43.imageshack.us/img43/5189/errorbh.jpg


Solution

  • Use a parametrized query. You will not have to worry about date formats and it will make your query SQL-injection-safe.

    string fileName = @"C:\mydb.accdb";
    string query = "UPDATE cas SET Odhod = ? WHERE sifra = ? AND Datum = ?";
    
    using (OleDbConnection conn = new OleDbConnection(
           "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName)) {
    
        OleDbCommand cmd = new OleDbCommand(query, conn);
    
        cmd.Parameters.AddWithValue("?", label1.Text);
        cmd.Parameters.AddWithValue("?", textBox1.Text);
        cmd.Parameters.AddWithValue("?", date);
    
        conn.Open();
        cmd.ExecuteNonQuery();
    }