Click here to Skip to main content
15,880,608 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Hi,
I have an SQLite table with 15 columns. I use 5 EditBoxes as input for searching desired information. The problem is that user may leave some of those EditBoxes empty and try to search their data based on few input fields. I want to write a query that supports this condition.

What I have tried:

<pre>SELECT * FROM PMinfo WHERE Column5 LIKE '%PCR%' AND Column7 LIKE '%1204%' AND 
Column9='True' AND Column13='Accepted' AND Column15 LIKE '%USA%';
Posted
Updated 9-Aug-21 0:16am
v2

1 solution

First off, don't do it like that. Never concatenate strings to build a SQL command. It leaves you wide open to accidental or deliberate SQL Injection attack which can destroy your entire database. Always use Parameterized queries instead.

When you concatenate strings, you cause problems because SQL receives commands like:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'Baker's Wood'
The quote the user added terminates the string as far as SQL is concerned and you get problems. But it could be worse. If I come along and type this instead: "x';DROP TABLE MyTable;--" Then SQL receives a very different command:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';DROP TABLE MyTable;--'
Which SQL sees as three separate commands:
SQL
SELECT * FROM MyTable WHERE StreetAddress = 'x';
A perfectly valid SELECT
SQL
DROP TABLE MyTable;
A perfectly valid "delete the table" command
SQL
--'
And everything else is a comment.
So it does: selects any matching rows, deletes the table from the DB, and ignores anything else.

So ALWAYS use parameterized queries! Or be prepared to restore your DB from backup frequently. You do take backups regularly, don't you?

Then when you have fixed that through your whole app, build your SQL WHERE condition by using a List<string>: if the textbox is empty, do nothing.
If it isn't, add the appropriate column name and the LIKE info to the collection:
C#
clauses.Add("Column5 LIKE '%@C5%');
Then add the column parameter to the SqLiteCommand.Parameters collection:
C#
cmd.Parameters.AddWithValue("@C5", textboxPCR.Text);
After the textboxes are all dealt with, add the clauses to your SQL command:
C#
cmd.CommandText = "SELECT * FROM PMinfo WHERE " + string.Join(" AND ", clauses);
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900