tags:

views:

71

answers:

3

My code is below. I have a method where I pass in three parameters and they get written out to an MS Access database table. However, I keep getting a syntax error message. Can anyone tell me why? I got this example from the internet.

        private static void insertRecord(string day, int hour, int loadKW)
    {
        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\LoadForecastDB.accdb";
        OleDbConnection conn = new OleDbConnection(connString);

        string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)";

        OleDbCommand cmd = new OleDbCommand(ins, conn);

        cmd.Parameters.Add("@day", OleDbType.VarChar).Value = day;
        cmd.Parameters.Add("@hour", OleDbType.Integer).Value = hour;
        cmd.Parameters.Add("@load", OleDbType.Integer).Value = loadKW;

        conn.Open();

        try
        {
            int count = cmd.ExecuteNonQuery();
        }
        catch (OleDbException ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            conn.Close();
        }
    }
+2  A: 

Try changing

string ins = @"INSERT INTO Forecasts (Day, Hour, Load) VALUES (?,?,?)"; 

To:

string ins = @"INSERT INTO Forecasts ([Day], [Hour], [Load]) VALUES (@day, @hour, @load)"; 
klausbyskov
I think OLE DB parameters need `?`, not @-prefixed names.
wRAR
Good idea! I'll change it now and see what happens. Thank you!
Kevin
Yes, I did read somewhere that OLE DB parms required ? instead of 'named' parms. But, I'll try anything at this point.
Kevin
@wRAR you might be right, however I read somewhere that you can use named params. Another point of my answer is to escape the names, Day, Hour and Load (using []).
klausbyskov
+6  A: 

I think this could be because your column names (Day and Hour) are also keywords. Maybe you can put ` (inverted single quotes) around them (that works in MySQL, don't know about MS Access)

Lex
Hmm. Day and Hour are keywords, eh? That may be the root of my problem. I'll change the field names in the file, and change my 'insert into' and see what happens. Thanks!
Kevin
I'm having second thoughts about it, could be that they aren't keywords, but it was the first thing I could think of. It's worth trying to find out, let me know what happens.
Lex
You were right! I changed Day and Hour to ForecastDay and ForecastHour in the file and the program and re-ran the program. It worked perfectly! Good eye! Thanks so much!
Kevin
A: 

Another option might be to refer bind variables with numbers:

    cmd.Parameters.Add(1, OleDbType.VarChar).Value = day;
    cmd.Parameters.Add(2, OleDbType.Integer).Value = hour;
    cmd.Parameters.Add(3, OleDbType.Integer).Value = loadKW;

Note I do not know C#, but similar approach works for Java and JDBC.

Juha Syrjälä
Thanks, Juha, I'll see if that makes a difference.
Kevin