how do I retrieve a result set from the database using a prepared statement? I have no idea how to continue from my codes, I managed to get the query and the variables for the prepared statement and now I'm stucked at retrieving from database.
Asked
Active
Viewed 74 times
1 Answers
3
You cannot pass field names as parameters. Only data can be passed like this. The condition
WHERE ?=?
-- ^
with substitutions Field1
and field1
will be interpreted literally, as
WHERE 'Field1'='field1' -- note the quotes around the values
If you would like to construct the condition from field names, you need to construct SQL string itself. For example, you could pass
SELECT * FROM Table1 WHERE %s=?
and use it as a format string for a formatter, passing Field1
for the argument to substitute %s
.
Be very careful for the names of fields not to be user-enterable: anything that becomes part of SQL string must come from a pool of constants in your program or its config file to avoid SQL injection attacks.

Sergey Kalinichenko
- 714,442
- 84
- 1,110
- 1,523
-
Oh i get it thanks ! But let's say if I want to display the result set out, how do i list them out from the fields that were passed ? – newbie95 Feb 13 '17 at 07:15
-
@dashblinkenlight Sorry i meant what if From another class it passed the query like "select Field1, Field2 from Table Where...." , How do i put the Field1 and Field2 (number of fields depending on query passed) into the prepared statement for me to retrieve the resultset? – newbie95 Feb 16 '17 at 03:34
-
@newbie95 Did you follow the link from the comment above? – Sergey Kalinichenko Feb 16 '17 at 03:42
-
Yes, I've done it but it prints out in the console, is there anyway to not print in console but return the result to another class? – newbie95 Feb 16 '17 at 06:05