Search code examples
c#oledb

working with access database update statment not working


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 thise update without Datum it works, but with Datum doesn't work. I'm connected to accesss database, and Datum field type in table is date/time Guys please help.

Hire is the program: https://www.dropbox.com/s/hx4zduvul8mh2uy/8.4.zip

Pictre of problem: http://img43.imageshack.us/img43/5189/errorbh.jpg


Solution

  • As usual, using string concatenation brings in a lot of trouble.
    (Sql Injection, Parsing problems)

    Just use parametrized queries

    string MyString = @"UPDATE cas SET Odhod= ? WHERE sifra = ? and Datum = ?"; 
    
    
    using(OleDbConnection cn = new OleDbConnection(connectionstring))
    using(OleDbCommand cmd = new OleDbCommand(MyString, cn)
    {
        cn.Open();
        cmd.Parameters.AddWithValue("@p1", label1.Text);
        cmd.Parameters.AddWithValue("@p2", textbox.Text);
        cmd.Parameters.AddWithValue("@p3", Convert.ToDate(date));
        cmd.ExecuteNonQuery();
    }
    

    Of course, the Date value stored in the Datum field should be exactly like the date passed in parameter @p3. Sometime it is good to add also the time value to your date

    string date= DateTime.Now.ToString("d.M.yyyy 00:00:00", ......);