the following line is the cause of the error, but I fail to spot where specifically it is wrong.
PreparedStatement stmt = connection.prepareStatement("SELECT (SEATS - RESERVATIONS) AS AVAIL FROM RESERVATIONS "
+ " CROSS JOIN (SELECT COUNT(FACULTY) WHERE FACULTY = ? AND DATE = ?) "
+ " WHERE SEATS = ?");
Followed by the error,
java.sql.SQLSyntaxErrorException: Syntax error: Encountered "WHERE" at line 1, column 93.
at org.apache.derby.client.am.SQLExceptionFactory.getSQLException(Unknown Source)
at org.apache.derby.client.am.SqlException.getSQLException(Unknown Source)
at org.apache.derby.client.am.ClientConnection.prepareStatement(Unknown Source)
at ReservationEntry.reserveRoom(ReservationEntry.java:30)
Reservation Entry is the file that the prepared statement is in, any help would be appreciated.
You need a FROM clause! Some databases require them. Something like this,perhaps:
SELECT (f.SEATS - r.RESERVATIONS) AS AVAIL
FROM RESERVATIONS R CROSS JOIN
(SELECT COUNT(FACULTY) as SEATS
FROM <table name goes here>
WHERE FACULTY = ? AND DATE = ?
) F
WHERE SEATS = ?;
I doubt this does anything useful, though, other than fix the syntax errors. You should ask a question with sample data, desired results, and an appropriate database tag.
Related
Just heard about 'SQL Hints' to optimize query's result or processing time at typing SQL queries.
I have found plenty of information about how to implement this concept into Hibernate, but nothing about how to use it with plain Java code.
Can anyone help me with this?
We are using the following code:
String value = "someValueToUseAsFilter";
String query = "SELECT /*+ opt_param('_optimizer_cost_model','io') opt_param('optimizer_index_cost_adj',20) opt_param('optimizer_index_caching',65) PARALLEL(4)*/ "+
" T.field AS table_field "+
" FROM table T "+
" WHERE T.field = ? "+
"/";
ResultSet rs = null;
PreparedStatement stmt = null;
try {
stmt = this.connection.prepareStatement(query);
stmt.setQueryTimeout(this.timeout);
stmt.setString(1, value);
rs = stmt.executeQuery();
}
catch (Exception e){
e.printStackTrace();
}
Next, eclipse is throwing the following exception:
java.sql.SQLSyntaxErrorException: ORA-00936: missing expression
The query has been tested and if launched directly against the database it works fine. But keeps returning this error when using it on code.
Can anyone explain me if this is even possible? If so, How can I use it in this context?
Thank you.
As explained in the answer #ahorse_with_no_name linked to, the / is a client directive to end and execute the statement. Your error is nothing to do with the hints or Java, you just need to remove that trailing slash.
You can see the same effect running your statement other ways, e.g. as dynamic SQL in an anonymous block:
set serveroutput on
declare
query varchar2(4000);
begin
query := q'[
SELECT /*+ opt_param('_optimizer_cost_model','io') opt_param('optimizer_index_cost_adj',20) opt_param('optimizer_index_caching',65) PARALLEL(4)*/
T.field AS table_field
FROM your_table T
WHERE T.field = :var
/
]';
dbms_output.put_line(query);
execute immediate query;
end;
/
The generated statement is printed as:
SELECT /*+ opt_param('_optimizer_cost_model','io') opt_param('optimizer_index_cost_adj',20) opt_param('optimizer_index_caching',65) PARALLEL(4)*/
T.field AS table_field
FROM your_table T
WHERE T.field = :var
/
with that trailing slash, and as you say that will run directly in a client/IDE; but the execute immediate gets the same error you do:
ORA-00936: missing expression
ORA-06512: at line 12
The slash is being seen purely as a division symbol, so it's expecting another expression after that - to make the clause WHERE T.field = :var / <something>.
If you remove the slash:
declare
query varchar2(4000);
begin
query := q'[
SELECT /*+ opt_param('_optimizer_cost_model','io') opt_param('optimizer_index_cost_adj',20) opt_param('optimizer_index_caching',65) PARALLEL(4)*/
T.field AS table_field
FROM your_table T
WHERE T.field = :var
]';
dbms_output.put_line(query);
execute immediate query using 42;
end;
/
the generated statement now doesn't have it (obviously), and you don't get the error:
PL/SQL procedure successfully completed.
(I should be selecting into something - the query is only parsed here, not executed, but that doesn't matter for this example).
Note that you also don't need a semicolon on the end of the statement, as that is a statement separator; adding one would cause a different error like ORA-00911 invalid character.
I've been having hard times finding the appropriate syntax for a prepared statement.
This is what I currently have:
String query = "SELECT * FROM TABLE1" + "WHERE Col1="+val1+ "AND Col2="+val2;
Can you please tell me what the actual syntax is, as I keep getting an SQL syntax error?
Thanks :)
There is no space between your table name and where clause.
String query = "SELECT * FROM TABLE1 WHERE Col1="+val1+ " AND Col2="+val2;
And if Col1 and COl2 are varchar then single quotes before and after val1 and val2.
String query = "SELECT * FROM TABLE1 WHERE Col1='"+val1+ "' AND Col2='"+val2+"'";
And better using parameters instead of giving values directly. It helps prevent SQL Injection attacks
Strange behavior.
We have the MSSQL server 2008 R2.
Our Java Servlet is calling a PreparedStatement with the following join.
... inner join Containstable (fulltextTable, mycolumn, ?) as KeyTable on id = KeyTable.[KEY] ...
Where ? = needle
This works fine.
But when i add two more arguments to Containstable like this:
... inner join Containstable (fulltextTable, mycolumn, ?, ?, ?) as KeyTable on id = KeyTable.[KEY] ...
Where ? = needle (Search for), ? = LANGUAGE N'German' (Language), ? = 250 (Limit result to 250 rows)
I get this exception:
java.sql.SQLException: Argument data type nvarchar is invalid for argument 4 of CONTAINSTABLE function.
This works fine in SQL Server Management Studio.
Is this a Problem with the SQLServerDriver in Java?
Cheers
Per
Here is my Code - this works:
if (contains!=null && contains.length()!=0) {
sql.append(" inner join Containstable( myFulltext, myColumn, ?) as KeyTable on id = KeyTable.[KEY]");
elementTypes.add(Types.NVARCHAR);
paramObject.add(contains);
//elementTypes.add(Types.NVARCHAR);
//paramObject.add("LANGUAGE N'German'");
//elementTypes.add(Types.BIGINT);
//paramObject.add(maxResults);
}
I suspect this is because the third 'parameter' to CONTAINSTABLE is not a normal, scalar parameter, it's a keyword (LANGUAGE) followed by a value.
Most likely JDBC is transforming LANGUAGE N'German' into 'LANGUAGE N''German''' and the resulting SQL is this, which is also invalid in SSMS:
...containstable(myTable, myColumn, 'needle', 'language N''German''', 250)
But of course it should be this:
...containstable(myTable, myColumn, 'needle', language N'German', 250)
You can confirm this guess by using SQL Profiler to trace the SQL actually being sent to the server. As for a solution, I don't know if JDBC will accept this:
...containstable(myTable, myColumn, ?, language ?, ?)
If it doesn't, you may have to use dynamic SQL to build a complete SQL string to execute, something like this (my quotes may not be completely correct, but you should get the idea):
set #sql = N'...containstable(myTable, myColumn, ''' + #search term + ''', language ''' + #language + ''', + cast(#rows as nvarchar(10)) + ')'
Unfortunately TSQL syntax is very inconsistent about where parameters are allowed and not, and this appears to be one such case.
I got the following error while testing some code:
SQLException: Invalid column index
What exactly does that mean?
Is there an online document explaining what all the Oracle error codes and statements?
If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.
For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.
It sounds like you're trying to SELECT a column that doesn't exist.
Perhaps you're trying to ORDER BY a column that doesn't exist?
Any typos in your SQL statement?
Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:
String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:
String sqlString = "select pwy_code from approver where university_id = ?";
I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this
SELECT * FROM EMPLOYE E WHERE E.ID = ?
and for the preparedStatement object (JDBC) if you set the parameters like
preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)
then it results in SQLException: Invalid column index
So, I removed that second parameter setting to prepared statement then problem solved
Just try this fix, as I faced your error:
Remove the single quotation marks around your question mark, which means, if you used your reserved parameters like ('?','?','?') you should make it look like this:
(?,?,?)
I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
the final sql statement is something like:
select col_1 from table_X where col_2 = 'abcd';
i run this inside my SQL IDE and everything is ok.
Next, i try to build this statement with java:
String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index
Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.
i just removed the characters that appear on white background
"select col_1 from table_X where col_2 = ' ? ' ; ";
to obtain
"select col_1 from table_X where col_2 = ?";
(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)
I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());
when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.
I got the following error while testing some code:
SQLException: Invalid column index
What exactly does that mean?
Is there an online document explaining what all the Oracle error codes and statements?
If that's a SQLException thrown by Java, it's most likely because you are trying to get or set a value from a ResultSet, but the index you are using isn't within the range.
For example, you might be trying to get the column at index 3 from the result set, but you only have two columns being returned from the SQL query.
It sounds like you're trying to SELECT a column that doesn't exist.
Perhaps you're trying to ORDER BY a column that doesn't exist?
Any typos in your SQL statement?
Using Spring's SimpleJdbcTemplate, I got it when I tried to do this:
String sqlString = "select pwy_code from approver where university_id = '123'";
List<Map<String, Object>> rows = getSimpleJdbcTemplate().queryForList(sqlString, uniId);
I had an argument to queryForList that didn't correspond to a question mark in the SQL. The first line should have been:
String sqlString = "select pwy_code from approver where university_id = ?";
I also got this type error, problem is wrong usage of parameters to statement like, Let's say you have a query like this
SELECT * FROM EMPLOYE E WHERE E.ID = ?
and for the preparedStatement object (JDBC) if you set the parameters like
preparedStatement.setXXX(1,value);
preparedStatement.setXXX(2,value)
then it results in SQLException: Invalid column index
So, I removed that second parameter setting to prepared statement then problem solved
Just try this fix, as I faced your error:
Remove the single quotation marks around your question mark, which means, if you used your reserved parameters like ('?','?','?') you should make it look like this:
(?,?,?)
I had this problem using a prepared statement. I didn't add enough "?" for the "VALUES" My eclipse had crashed after I did add the proper amount, and lost those changes. But that didn't occur to me to be the error until I started combing through the SQL as p.campbell suggested.
I had the exact same problem when using Spring Security 3.1.0. and Oracle 11G. I was using the following query and getting the invalid column index error:
<security:jdbc-user-service data-source-ref="dataSource"
users-by-username-query="SELECT A.user_name AS username, A.password AS password FROM MB_REG_USER A where A.user_name=lower(?)"
It turns out that I needed to add: "1 as enabled" to the query:
<security:jdbc-user-service data-source-ref="dataSource" users-by-username query="SELECT A.user_name AS username, A.password AS password, 1 as enabled FROM MB_REG_USER A where A.user_name=lower(?)"
Everything worked after that. I believe this could be a bug in the Spring JDBC core package...
the final sql statement is something like:
select col_1 from table_X where col_2 = 'abcd';
i run this inside my SQL IDE and everything is ok.
Next, i try to build this statement with java:
String queryString= "select col_1 from table_X where col_2 = '?';";
PreparedStatement stmt = con.prepareStatement(queryString);
stmt.setString(1, "abcd"); //raises java.sql.SQLException: Invalid column index
Although the sql statement (the first one, ran against the database) contains quotes around string values, and also finishes with a semicolumn, the string that i pass to the PreparedStatement should not contain quotes around the wildcard character ?, nor should it finish with semicolumn.
i just removed the characters that appear on white background
"select col_1 from table_X where col_2 = ' ? ' ; ";
to obtain
"select col_1 from table_X where col_2 = ?";
(i found the solution here: https://coderanch.com/t/424689/databases/java-sql-SQLException-Invalid-column)
I had this problem in one legacy application that create prepared statement dynamically.
String firstName;
StringBuilder query =new StringBuilder("select id, name from employee where country_Code=1");
query.append("and name like '");
query.append(firstName + "' ");
query.append("and ssn=?");
PreparedStatement preparedStatement =new prepareStatement(query.toString());
when it try to set value for ssn, it was giving invalid column index error, and finally found out that it is caused by firstName having ' within; that disturb the syntax.