tags:

views:

52

answers:

2

I was wondering if there was anyway to specify returned column names using prepared statements.

I am using MySQL and Java.

When I try it:

String columnNames="d,e,f"; //Actually from the user...
String name = "some_table"; //From user...
String query = "SELECT a,b,c,? FROM " + name + " WHERE d=?";//...
stmt = conn.prepareStatement(query);
stmt.setString(1, columnNames);
stmt.setString(2, "x");

I get this type of statement (printing right before execution).

SELECT a,b,c,'d,e,f' FROM some_table WHERE d='x'

I would like to see however:

SELECT a,b,c,d,e,f FROM some_table WHERE d='x'

I know that I cannot do this for table names, as discussed here, but was wondering if there was some way to do it for column names.

If there is not, then I will just have to try and make sure that I sanitize the input so it doesn't lead to SQL injection vulnerabilities.

Thank you so much for your help! This site is a really great resource!

A: 

I think this case can't work because the whole point of the prepared statement is to prevent the user from putting in unescaped query bits - so you're always going to have the text quoted or escaped.

You'll need to sanitize this input in Java if you want to affect the query structure safely.

Greg Harman
+3  A: 

This indicates a bad DB design. The user shouldn't need to know about the column names. Create a real DB column which holds those "column names" and store the data along it instead.

At any way, no, you cannot set column names as PreparedStatement values. You can only set column values as PreparedStatement values. If you'd like to continue in this direction, you need to sanitize the column names and concatenate/build the SQL string yourself. Quote the separate column names and use String#replace() to escape the same quote inside the column name.

BalusC
Well, the user doesn't actually need to know the column names, but the column names needed are deduced based on forms submitted by the user. This is handled on the client side, though, so I wanted to see if there was some way to ensure the data is safe. Should I then just move the whole lot to the server-side, thereby ensuring the column data is untainted?
KLee1
Handle it on the server side instead. Don't do business stuff in client side.
BalusC