0

I am trying to create a filter function for a web-based app that relies on SQLite for persistent storage. I am trying to use a prepared statement, but it has to be created dynamically based on the number of boxes checked by the user. I have an query created to which I dynamically add ? placeholders (using the suggestion from IN clause and placeholders).

I've gotten as far as creating the correct number of ?s in the correct places, but I cannot figure out how to then add the values to the parameters inside the [...]'s.

When I use a variable that holds all of the parameter values inside the [...], I get an error "number of '?'s in statement string does not match argument string". I've also tried using one variable for each of the sets of placeholders. That did not work, either. I suppose that the number of placeholders is checked against the number of parameters and an error returned before the variables are read.

// just spaced it with returns and removed the +'s and "'s to make it easier to read
var filterQuery =   SELECT t1.col1, t1.col2, t1.col3, t2.col2, t3.col2
                    FROM t1, t2, t3
                    WHERE t1.col2 = ? 
                    AND t1.col3 IN ( ?, ?, ?)
                    AND t2.col2 IN ( ?, ?, ?, ?)

code:

db.transaction(function(tx) {
    tx.executeSql(
        filterQuery,
        [/* what do I put in here so that the number of ?s matches with the number of parameters? */],
        success,
        failure
    );
});

How can I dynamically insert the parameters so that they match the number of placeholders and the mismatch error is avoided?

Clarification: I have successfully run the queries without prepared statements. I'm hoping for a solution that will allow me to use them.

(bonus question - will this query do what I am hoping it will do, i.e., grab only the rows that match all the selections that the user has made?)

Thanks in advance!

Community
  • 1
  • 1
salsbury
  • 2,777
  • 1
  • 19
  • 22

1 Answers1

0

Fastest way is to use actual parameter values inside your dynamic SQL instead of question marks (?), e.g.

WHERE t1.col2 = 'searchstring' 
AND t1.col3 IN ( 12, 23, 24)
AND t2.col2 IN ( 'value', 'onemorevalue', 'x', 'y')
Michael Petrotta
  • 59,888
  • 27
  • 145
  • 179
KolA
  • 707
  • 7
  • 15
  • But then you won't be able to use a prepared statement (since your statements will differ every time, forcing the SQL engine to parse the statement every time you execute it), and you have to worry about SQL injection. – Frank Schmitt Jul 26 '12 at 08:42
  • Correct, but it seems like statement is already not static ("depends 've gotten as far as creating the correct number of ?s in the correct places"). As I said it is faster way, but not best ;) – KolA Jul 26 '12 at 09:41