In my java application I am using OPENQUERY to execute an SQL query in remote linked MSSQL server and fetch result. Below is an example of OPENQUERY I am using:
SELECT 1 FROM OPENQUERY('LINK_SERVER1', 'SELECT 1 FROM TABLE_ABC');
In my Java class I am using PreparedStatement as below to execute the above OPENQUERY as below:
String linkServerName = "LINK_SERVER1";
String remoteQuery = "'SELECT 1 FROM TABLE_ABC'";
String openQuery = "SELECT 1 FROM OPENQUERY(" + linkServerName + ", " + remoteQuery + ")";
PreparedStatment ps = connection.prepareStatement(openQuery);
ps.executeQuery();
The above code works as expected. However the problem is that it is liable for SQL Injection and HP Fortify reports it as SQL Injection vulnerable.
I attempted to change the above code to use setString on PreparedStatement as below.
String linkServerName = "LINK_SERVER1";
String remoteQuery = "'SELECT 1 FROM TABLE_ABC'";
String openQuery = "SELECT 1 FROM OPENQUERY(?, ?)";
PreparedStatment ps = connection.prepareStatement(openQuery);
ps.setString(1, linkServerName);
ps.setString(2, remoteQuery);
ps.executeQuery();
However the above code does not work as I expect it to. At run time I get below exception on call to ps.executeQuery():
java.sql.SQLException: Incorrect syntax near '#P0'.
I am not clear what is incorrect with above code. It seems that the MSSQL jdbc driver isn't liking it, and call to setString method on PreparedStatement did not set the parameter correctly.
Has anyone come across this issue and resolved it? Any pointers towards the resolution of this is appreciated.
java.sql.SQLException: Incorrect syntax near '#P0'.
at net.sourceforge.jtds.jdbc.SQLDiagnostic.addDiagnostic(SQLDiagnostic.java:365)
at net.sourceforge.jtds.jdbc.TdsCore.tdsErrorToken(TdsCore.java:2781)
at net.sourceforge.jtds.jdbc.TdsCore.nextToken(TdsCore.java:2224)
at net.sourceforge.jtds.jdbc.TdsCore.getMoreResults(TdsCore.java:628)
at net.sourceforge.jtds.jdbc.JtdsStatement.executeSQLQuery(JtdsStatement.java:418)
at net.sourceforge.jtds.jdbc.JtdsPreparedStatement.executeQuery(JtdsPreparedStatement.java:693)
at com.mchange.v2.c3p0.impl.NewProxyPreparedStatement.executeQuery(NewProxyPreparedStatement.java:76)
at com.aviseurope.rm.fcst.modules.service.HealthCheckServiceImpl.canConnectToBiSsde(HealthCheckServiceImpl.java:658)
I have a preparedStatement for select query in mySQL.
this is what I wrote:
String sQuery = "SELECT Password FROM test WHERE Email = ?";
st = DB.prepareStatement(sQuery);
st.setString(1, email);
ResultSet rs = st.executeQuery(sQuery);
but i'm getting an exception from the glassfish server that says:
Severe: com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException:
You have an error in your SQL syntax; check the manual that corresponds
to your MySQL server version for the right syntax to use near '?' at line 1
I don't understand what is the problem.. all the samples i saw, use that syntax..
You must call st.executeQuery(), without the query as argument. The query has already been passed to the statement when it was prepared.
See http://docs.oracle.com/javase/7/docs/api/java/sql/PreparedStatement.html#executeQuery%28%29
st.executeQuery() i.e. no param to executeQuery
in query "_latin" is getting concatenated before every param
java code :
PreparedStatement prepStmt = null;
QueryString = "SELECT FROM Student WHERE username=? AND password=? ";
prepStmt=con.prepareStatement(QueryString);
prepStmt.setString(1,un);
prepStmt.setString(2,pwd);
ResultSet rs;
System.out.println(prepStmt);
rs = prepStmt.executeQuery();
error :
java.sql.SQLException: [MySQL][ODBC 5.1 Driver][mysqld-5.5.24-log]You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'FROM Student WHERE username=_latin1'wow' AND password=_latin1'hell'' at line 1
why its happening , whats the solution
and this is table :
You are missing the column list from your query. You have to either specify explicitly the columns you want, or retrieve all via wildcard. Instead of:
SELECT FROM Student WHERE username = ? AND password = ?
You want something like:
SELECT * FROM Student WHERE username = ? AND password = ?
Note that its almost always better to explicitly define the columns you want to retrieve, rather than using the wildcard expression.
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 am working on a mini application and I have to retrieve and save USER_ID in a table.
It works like this; I input the email address of the user and then the statement has to retrieve USER_ID and save it into a table.
I am having problem with my SQL Like statement. Its just that I have to insert only the first part of the email address. For example, "thomas#yahoo.com". I insert only "thomas"; not remaining part.
Here are sample of the statement and resulting message I am getting in my Java console:
Code:
String ea = txt_email.getText();
String lid = "SELECT USER_ID FROM user WHERE email_address Like '"+ea+"%' ";
Error Message:
Error: java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Syntax error (missing operator) in query expression ''SELECT USER_ID FROM user WHERE email_address Like 'thomas%' ''.
Try using * instead of %. MS ACCESS uses * instead of % for the LIKE statement.
Hope this helps
use PreparedStatement
PreparedStatement _query = con.prepareStatement(
"SELECT USER_ID FROM user WHERE email_address Like ?");
_query.setString(1, ea + "*"); // <== use *
_query.executeQuery();
where con is your active connection object.
One advantage of using PreparedStatement is protect from SQL Injection