Problem using jsp to query MS SQL server database

I have a database already set up with columm EventID being int (integer). I use the following code to retrieve data:

int TestNumber=123;

String sqlqry = "select Date, starttime, endtime from timeTable where EventID = TestNumber";

PreparedStatement pstmt = null;

ResultSet result = null;

pstmt = con.prepareStatement(sqlqry);

result = pstmt.executeQuery();

It does not work. But in String statement, I replace TestNumber by a specific number as follows, it works fine

String sqlqry = "select Date, starttime, endtime from timeTable where EventID = 123";

Anybody can help, thanks a lot.

[646 byte] By [Danny_55a] at [2007-11-26 19:51:49]
# 1

Learning how to program by using JDBC and JSP is going to be very difficult.

> It does not work.

It tells you why if you print the exception.

1. int TestNumber=123;

2. String sqlqry = "select ... from timeTable where EventID = TestNumber";

The literal 'TestNumber' in lines 1 and 2 have absolutely NOTHING to do with each other. In line one it is a java variable. In line two it is an sql identifier which has no meaning and thuse it will cause an exception.

jschella at 2007-7-9 22:42:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 2
Thanks for your explanation. But how to solve this problem? In my case, that number is only determined within some circumstance and I must use it to retrieve data accordingly. Any suggestion? Thanks.
Danny_55a at 2007-7-9 22:42:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 3
You use the prepared statement correctly. That requires using a bind variable (a '?') and then setting the value with the appropriate method.
jschella at 2007-7-9 22:42:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 4

HI,

Try this

int TestNumber=123;

String sqlqry = "select Date, starttime, endtime from timeTable where EventID = "+TestNumber;

PreparedStatement pstmt = null;

ResultSet result = null;

pstmt = con.prepareStatement(sqlqry);

result = pstmt.executeQuery();

Regards,

Ram.

Message was edited by:

JTech

JTecha at 2007-7-9 22:42:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...
# 5
jschell/JTech,Thank you guys so much.I have tried Ram's option and it works perfectly.I understand that there must be other solutions for this but the option that Ram suggested could be the most simple.Once again, thanks and regards.
Danny_55a at 2007-7-9 22:42:10 > top of Java-index,Database Connectivity,Java Database Connectivity (JDBC)...