Win a copy of Functional Reactive Programming this week in the Other Languages forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Passing variables

 
Ahmed Haboubi
Ranch Hand
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 13459
Android Eclipse IDE Ubuntu
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1879
MySQL Database Suse
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 36
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Excuse my ignorance guys, but what's a PreparedStatement and how can I use it??
I've never programmed an application that uses JDBC.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic