File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes JDBC and Relational Databases and the fly likes Passing variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Databases » JDBC and Relational Databases
Bookmark "Passing variables" Watch "Passing variables" New topic

Passing variables

Ahmed Haboubi
Ranch Hand

Joined: Oct 21, 2000
Posts: 36
I'm trying to pass variables to a table in SQL 7.0 using the following statement:
stmt.execute("insert into table_name values(i,j)"); //Assume that all variables and objects are declared correctly.
This works fine when I send numbers like 100 or 5. But I get the follwing run-time exception when trying to execute the above statement:
Exception in thread "main" java.sql.SQLException: [Microsoft][ODBC SQL Server Driver][SQL Server]The name 'i' is not permitted in this context. Only constants, expressions, or variables allowed here. Column names are not permitted.
Please advise. Thank you.
Ahmed Haboubi
Ranch Hand

Joined: Oct 21, 2000
Posts: 36
OK, I got it !!
The statement should be concatenated with the variables like this:
stmt.executeUpdate("insert into table1 values("+ i + "," + j + ")");
Now it's working
David O'Meara

Joined: Mar 06, 2001
Posts: 13459

Or you could start using PreparedStatements.
A couple of lines of extra code but they end up saving heaps of trouble in the long run.
Jamie Robertson
Ranch Hand

Joined: Jul 09, 2001
Posts: 1879

I agree with Dave. Just wait until you start inserting values like "O'Meara" into the database. You'll wished you used a preparedStatement then!
There is no performance difference in using a Statement over a PreparedStatement when executing a single query(based on tests that I have done from creation to execution). But if you can reuse a PreparedStatement, there is significant performance gain over a Statement. And as I eluded to earlier, PreparedStatements deal with special characters for you.
Go PreparedStatements!
Ahmed Haboubi
Ranch Hand

Joined: Oct 21, 2000
Posts: 36
Excuse my ignorance guys, but what's a PreparedStatement and how can I use it??
I've never programmed an application that uses JDBC.
I agree. Here's the link:
subject: Passing variables
It's not a secret anymore!