Skip to content
Advertisement

Unexpected token when creating a string expression?

I have the following code:

public void UpdateCardSetColumn(CARD cardColumn, bool value, string cardId)
{
    string strValue = value ? "1" : "0";

    sql = $"UPDATE Card SET {cardColumn.Text()} = {strValue}​ WHERE CardGuid = '{​cardId}​'";

    RunExecute(db2, sql);
}

There is an error here '{cardId

And it tells me

Invalid Expression term “

Advertisement

Answer

You need to be aware that this kind of string concatenation is avoided and it is open to SQL Injection attack, you should always use parameterized queries to avoid SQL Injection and also to get rid of errors, something like this:

sql = "UPDATE Card SET cardColumn = @strValue​ WHERE CardGuid = @​cardId";
yourSqlCommand.Parameters.AddWithValue("@strValue​ ", cardColumn.Text);
yourSqlCommand.Parameters.AddWithValue("@​cardId", ​cardId);

Although specifying the type directly and using the Value property is better than AddWithValue:

yourSqlCommand.Parameters.Add("@​cardId", SqlDbType.VarChar).Value = ​cardId;

Read more here: https://blogs.msmvps.com/jcoehoorn/blog/2014/05/12/can-we-stop-using-addwithvalue-already/

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement