Search code examples
c#sqloledb

C# OleDb sql "UPDATE, WHERE" exception


So I have the following code :

public static void WriteToDatabase(string sql,string value,int Amount, string URL)
    {
int times = int.Parse(((dr)[dt.Columns[1]]).ToString()) + Amount;
                    sql = "UPDATE Words "+
                          " SET Amount = " + times + 
                          " WHERE Word = " + value + 
                          " AND Website = " + URL + ";";
myAdp = new OleDbDataAdapter();
myAdp.InsertCommand = new OleDbCommand(sql, myConn);
                    myAdp.InsertCommand.ExecuteNonQuery();
}

Which supposed to update a value in a pre-made Microsoft Access 2007 file, and whenever I run the code they following OleDb exception occurs :

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll , Syntax error missing operator in query expression : 'Word = meta AND Website = http://www.twitch.tv/directory'." "

So I've searched the web for common errors that could happen, and I couldn't find any, I'll be glad if someone can find the mistake in the sql. Thanks.


Solution

  • You absolutely should be using parameterized queries for this. That is the right way to pass values in.

    Your problem is that your query is missing single quotes:

    "UPDATE Words "+
                          " SET Amount = " + times + 
                          " WHERE Word = '" + value + "'" +
                          " AND Website = '" + URL + "'"
    

    But let me re-emphasize that although this should work, you should fix the code so it uses parameters