Alan2
Alan2

Reputation: 24572

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 "

Upvotes: 0

Views: 442

Answers (2)

Salah Akbari
Salah Akbari

Reputation: 39966

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/

Upvotes: 5

Alan2
Alan2

Reputation: 24572

The problem was fixed when the line was entered again. There must have been some non-ascii character in the text as it's working good now.

Upvotes: 0

Related Questions