aspose file tools*
The moose likes JDBC and the fly likes Passing variables Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Java 8 in Action this week in the Java 8 forum!
JavaRanch » Java Forums » Databases » JDBC
Bookmark "Passing variables" Watch "Passing variables" New topic
Author

Passing variables

Ahmed Haboubi
Ranch Hand

Joined: Oct 21, 2000
Posts: 36
Hi,
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.
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
Ahmed.
David O'Meara
Rancher

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.
Dave.
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!
Jamie
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: http://aspose.com/file-tools
 
subject: Passing variables
 
Similar Threads
Escape characters for variables in sql
join sql statements
Error in output
ORA-01008: not all variables bound
Cannot perform SQL UPDATE null