20

I am trying to do an SQL query such as

SELECT * FROM [TABLE] WHERE hostname LIKE '%myhostname%';

This works fine in plain SQL, but when I use System.Data.SQLite in C#, it only works with a literal, not a parameter, such as

string sel = "SELECT * FROM [TABLE] WHERE hostname LIKE '%@host%'";
...
command.Parameters.AddWithValue("@host", "myhostname");

This returns no results.

2 Answers 2

35

You can't do that. The parameters must be complete values - it's not just a string substitution into the SQL. You could do this instead:

string sel = "SELECT * FROM [TABLE] WHERE hostname LIKE @host";
...
command.Parameters.AddWithValue("@host", "%myhostname%");
Sign up to request clarification or add additional context in comments.

5 Comments

string sel = "SELECT * FROM [TABLE] where hostname like '%'+@host+'%'"; would also work.
Thanks Mark - this helped a ton. Donnie - I tried this earlier and it didn't seem to work for me.
just encountered the same situation in Ruby with Sqlite3, and your solution worked like a champ there too. Upvote, which was for some reason met with a kick-line of ponies on my screen? :/
@Donnie, your statement works, but I had to use concatenation with || instead of +
It Worked. Cool. :)
18

Easiest way to do this is to use '||'

Use :

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName || '%' ";

Instead Of:

const string qry = "SELECT SiteNum FROM WorkTable WHERE WTName LIKE @wtName%";

I have already answered here

1 Comment

Thanks for this! I was looking for a way to do it workout having to put the "%" characters into the search parameter value. I see that @Thunderforge commented on the accepted answer basically saying what you've said here, but I wouldn't have noticed that without seeing your answer first.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.