iTEgg
iTEgg

Reputation: 8342

SQL query parameterization

Could someone give an answer to the following please?

Statement statement;

string sql;

sql = "SELECT gender FROM people WHERE gender = 'M' ";

results = statement.executeQuery(sql);

What kind of formatting do I have to do to represent 'M' in my string SQL query?

Notes: gender is either 'M' or 'F' and I want to return all rows that are of gender 'M'.

Upvotes: 0

Views: 117

Answers (1)

Aaron Digulla
Aaron Digulla

Reputation: 328556

'M' is the correct way to specify a value for a VARCHAR column if you write the query manually.

But a better way is usually to use a prepared statement:

stmt = connect.prepareStatement("SELECT gender FROM people WHERE gender = ?");
stmt.setString( 1, "M" );

The advantage of this approach is that JDBC will automatically convert the parameter for you, escape it properly, etc.

For example, your code will become much more complex for people's names after you tried to add D'Angelo (common Italian name) to your database.

Upvotes: 1

Related Questions