Intermittently getting "sqlexception invalid column index" [duplicate] - java

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.

Related

2-parameter PreparedStatement is throwing syntax error, SQL State 42601, near second argument [duplicate]

This question already has an answer here:
Using parameter values for schema and table in Postgresql
(1 answer)
Closed 2 years ago.
I am creating a simple java application that uses a postgresql database which I have already created (the database has been created, not the application).
One of the TABLEs is called 'Employee'.
It has an attribute called 'eid', short for employee id.
I am trying to use a PreparedStatement to generalize a database SELECT query. I want there to be two parameters which are generalized. I would also like to get the length of the result, so I created a second PreparedStatement to find that.
The code seems quite simple, but I keep getting the same syntax error.
Here is the code I am trying to run:
public static String[] select(Connection conn, String arguments) {
try {
PreparedStatement preparedSelect = conn.prepareStatement("SELECT ? FROM ?");
PreparedStatement preparedCount = conn.prepareStatement("SELECT COUNT(*) FROM ?");
String[] arrOfStr = arguments.split(" ", 0);
System.out.println(arrOfStr[0].equals("eid"));
System.out.println(arrOfStr[1].equals("Employee"));
preparedSelect.setString(1, arrOfStr[0]);
preparedSelect.setString(2, arrOfStr[1]);
preparedCount.setString(1, arrOfStr[1]);
ResultSet rsSelect = preparedSelect.executeQuery();
ResultSet rsCount = preparedCount.executeQuery();
...
In the first line's argument, I would like the SELECT query to be: "SELECT eid FROM Employee".
In the second line's argument, I would like the SELECT query to be: "SELECT COUNT(*) FROM Employee".
The user who uses this application enters (earlier in the program) the "arguments" argument found in the arguments of the "select" function. The "arrOfStr" string array will contain these two strings, "eid", and "Employee".
To check that "arrOfStr" has the correct values, I printed the booleans resulting from the .equals() function comparing the values to the strings I want which, again, are "eid", and "Employee".
In the console the results are, not to my surprise:
true
true
Thus, in the next 3 lines, I set the String values "eid" and "Employee" into the PreparedStatements.
Finally, I execute the queries in the following 2 lines. Both of these query executions (I have tried switching them around) give me a very similar error. For the given code I get the error:
SQL State: 42601
ERROR: syntax error at or near "$2"
Position: 16
This is stating that there is an issue with the syntax of the string "Employee".
When I go directly to my postgresql database, and input:
SELECT eid FROM Employee;
I get the output:
1663
1983
1357
...
Could someone explain this syntax error?
As mentioned by Elliott, you cannot bind the table name that way.
To achieve your goal, try this:
String[] arrOfStr = arguments.split(" ", 0);
PreparedStatement preparedSelect = conn.prepareStatement("SELECT ? FROM " + arrOfStr[1]);
PreparedStatement preparedCount = conn.prepareStatement("SELECT COUNT(*) FROM " + arrOfStr[1]);

Java and MYSQL Syntax Issue

I'm trying to insert data into my MYSQL databse. I want to insert an int into the database which I have no problem doing. However, I want to INSERT INTO (VALUES) WHERE. I get a MYSQL syntax error when I try this.
I can INSERT and SELECT WHERE as long as they are in two seperate statements. Here is my code:
String query = ("INSERT INTO `accounts` (inventory) " + "VALUES ('"
+ Inventory.inventory + "') WHERE username='" + Frame.username
+ "' and password = '" + Frame.password + "'");
Basically, an INSERT statement can not have a WHERE clause. I am thinking that you want to UPDATE a certain record, eg
UPDATE accounts
SET inventory = 'valueHere'
WHERE userName = 'userHEre' AND password = 'passHere'
The only time an INSERT statement can have a WHERE clause is when you are inserting records from the result of a SELECT statement, eg
INSERT INTO tableName (col1, ..., colN)
SELECT col1, ..., colN
FROM table2
// WHERE ..your conditions here..
As a sidenote, your current coding style is vulnerable with SQL Injection. Consider using PreparedStatement.
Basic example of a PreparedStatement
String updateString = "UPDATE accounts SET inventory = ? WHERE userName = ? AND password = ?";
PreparedStatement updateStmt = con.prepareStatement(updateString);
updateStmt.setString(1, Inventory.inventory);
updateStmt.setString(2, Frame.username);
updateStmt.setString(3, Frame.password);
updateStmt.executeUpdate();
JDBC PreparedStatement
MySQL INSERT Syntax does not support the WHERE clause so that's why you have a syntax issue. Maybe you're looking for an UPDATE :
UPDATE [LOW_PRIORITY] [IGNORE] tbl_name
SET col_name1=expr1 [, col_name2=expr2 ...]
[WHERE where_definition]
[ORDER BY ...]
[LIMIT row_count]
Not a direct answer but more of a best practice....
You should avoid doing this type of string concatenation for any sql. You vulnerable to sql injection and it does not scale well. Instead you should look at using JdbcTemplates or NamedJdbcTemplate using the opensource spring framework.
The WHERE is not applicable in INSERT INTO Syntax. You want insert a new row in the table, and you should add the username and password as well as Inventory.inventory in VALUES set.

Using MySQL like for Column name

I want to write a mysql select query using preparedstatement. But theres syntax error at the last part which is concat('%', itemName, '%')"; itemName is a column of table ItemMain.
I already tried 3 queries given below.
String sql ="SELECT * FROM ItemMain WHERE ? = 'All' OR ? like concat('%', itemName, '%')";
String sql ="SELECT * FROM ItemMain WHERE ? = 'All' OR ? like '%'+itemName+'%'";
String sql ="SELECT * FROM ItemMain WHERE ? = 'All' OR ? like '%itemName%'";
You can't use placeholders for field names. The queries would have to be
... WHERE somefield=? OR otherfield LIKE concat('%', ?, '%')
placeholders are for VALUES only. field/table names, function namesm or any of the "Structural" words in SQL are offlimits.
This is a general rule for mysql prepared statements. It is not a java/php/c#/whatever restriction.
Although #Marc B is absolutely right (+1) I would like to add something. I believe that your have a real task where you need such functionality, so I would like to suggest you the following solution.
You can create query dynamically as following. If you are using plain JDBC you can run query like desc YOUR_TABLE_NAME. It will return a easy-to-parse list of fields in your table. You can implement your "like" statement yourself either using regular expression or simple string manipulation methods as startsWith("xyz") instead of like 'xyz%', endsWith("xyz") instead of like '%xyz' and contains("xyz") instead of like '%xyz%'. Now you can create SQL statement dynamically by adding fields the meet your requirements.
Found the answer to my problem.
String sql ="SELECT * FROM ItemMain WHERE ? = 'All' OR itemName like '%"+keyword+"%'";
Object []values ={keyword};
ResultSet res = DBHandller.getData(sql, conn, values);
I swapped the column name, keyword and change the syntax here '%"+keyword+"%'";
Now it works fine. thnx al

issue in query with preparedstatement in java with mysql

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.

What does the following Oracle error mean: invalid column index

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.

Categories

Resources