SQL statements

Hey,

Ive been trying to insert a string variable into a SQL statement but as of yet with no luck. I know how to do it using VB but not in java. Heres a example in VB of what i need to do in java:

String position = "manager";

String SQL = " Select * from employees where position = ' " & position & " ' ";

So far the { ' " & position & " ' "} does not work in java, does any one have a solution to this. I was just goin to append the position onto the end of the SQL and leave it be but id prefer a better solution to that.

I can try and make it more clear if it will help!

Mike

[640 byte] By [michaeln31a] at [2007-11-26 15:42:10]
# 1

Hello, you concatenate strings using the + operator in java:

String sql = "select * from table where id='" + id + "'";

However you should look into using a PreparedStatement (to avoid SQL injection for one):

String sql = "select * from table where id = ?";

PreparedStatement ps = con.prepareStatement( sql );

ps.setInt( 1, id );

ResultSet rs = ps.executeQuery();

mrlogitecha at 2007-7-8 22:00:54 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2

> Hey,

>

> Ive been trying to insert a string variable into a

> SQL statement but as of yet with no luck. I know how

> to do it using VB but not in java. Heres a example in

> VB of what i need to do in java:

You concatenate Strings in Java like this:

String position = "manager";

String SQL = " Select * from employees where position = ' " + position + " ' ";

> So far the { ' " & position & " ' "} does not work

Never will. Learn the language you're writing.

The suggestion to learn how to use PreparedStatement is the correct answer for this particular case. You need to learn about Strings in general if you're going to write Java.

%

duffymoa at 2007-7-8 22:00:54 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3

String SQL = " Select * from employees where position = ' " + position + " ' ";

Well, because

' manager '

isn't the same as

'manager'

Your example wont work.

mrlogitecha at 2007-7-8 22:00:54 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4
true enough. cut & pasted from the original, so it's as incorrect as the one the OP posted.plenty of other things wrong, like "SELECT *". One problem at a time.%
duffymoa at 2007-7-8 22:00:54 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5

Thanks mrlogitech, the prepared statement worked even better, forgot about them!

Oh yah that example was just an example! and "Select" works fine with MySQL, its not picky with upper case or lower case as long as your names are in the correct case.

Thanks for all the help!

Mike

michaeln31a at 2007-7-8 22:00:54 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...