Java and MYSQL Syntax Issue - java

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.

Related

JDBC - NetBeans x MySQL

I'm trying to create a Java Application in NetBeans which allows the user to use most MySQL RDBMS functionalities through a GUI. I have successfully written the code for the following :
Creating a Database
Dropping a Database
Creating a Table giving options for table name, no. of columns, data type for every column
I'm stuck at the part where the user gets to insert a record in the table that was just created. I'm unable to figure out how the "insert into table values ..." query can be dynamically created and passed depending on the table the user wants to enter this record in. The table could have any number of columns, of course.
I dont know if this is the correct method, but when I faced this same problem in the past, this is how I solved it :
I ran this query to find the number of columns in the table
SELECT COUNT(*) FROM INFORMATION_SCHEMA.COLUMNS WHERE table_catalog = 'database_name' AND table_name = 'table_name'
Then created a dynamic sql query based on no of columns:
String sql = "Insert into tablename values(";
for(int i = 1;i<=columns;i++){
sql += "?";
if (i < columns) {
sql += ", ";
}
}
sql+=");";
Then fired a Prepared Statement
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
If you also don't know the constraints and datatype of the columns, try parsing
desc tablename
I know this must be the shittiest workaround, but it worked for me;)

JDBC Select from 2 columns within the same table

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

Insert data to sql using java issue

I'm facing an issue with insertion to SQL database from java code.
I'm using INSERT sql query using the java code to enter the data from XML file to SQL database.
You may suppose column named "Description".
Imagine there is a record in XML which contains apostrophe ('). The program crashes due to the error caused by the apostrophe which is included in the data.
I know that manually we can add another apostrophe and make it work, but imagine data of 10.000 records, how can we handle this issue?
Don't do this (string concatenation):
String sql = "insert into MyTable (description) values ('" + value + "')";
Statement st = connection.createStatement();
st.executeUpdate(sql);
Do do this (prepared statement):
PreparedStatement ps = connection.prepareStatement(
"insert into MyTable (description) values (?)"
);
ps.setString(1, value);
pt.executeUpdate();
The value will get correctly escaped for you. Not only does this protect against mishaps like the one you mentioned, it also helps defend you from SQL injection attacks.
Humorous illustration:
Source
You have two options, you should use PreparedStatement and bind your parameter(s). Or, if you really, really, want - you could use StringEscapeUtils.escapeSql(str).

Intermittently getting "sqlexception invalid column index" [duplicate]

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.

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