Hey I have problem with preparedStatement, I want to find min for few columns, I'm iterating over the names of columns and inserting them inside my preparedStatement like that
connection.prepareStatement("SELECT min( ? ) as min FROM test");
minStatement.setString(1, "some_column");
and when retrieving from ResultSet I'm getting the column name, in this case the result is "some_column" and should be 0. When using normal statement it does return right value.
I have no idea what I'm doing wrong.
Thanks for any help.
You cannot specify a column name in prepared statement like this, what you get is:
SELECT MIN('some_column') AS min FROM test
Instead of:
SELECT MIN(some_column) AS min FROM test
So, your query selects the minimal value 'some_column'... which is 'some_column'.
You could, instead, try that:
connection.prepareStatement("SELECT min(" + some_column + " ) as min FROM test");
But this may lead to injection attacks.
Related
I am creating a new register in table MY_TABLE using java and then, I am doing a query to obtain the max(id) of that table. However, Java is obtaining the previous one. I mean:
mybean.store(con)
con.commit();
pstm = con.prepareStatement("SELECT MAX (ID) FROM MY_TABLE");
rs = pstm.executeQuery();
while (rs.next()){
id = rs.getString("ID");
System.out.println("id: " +id);
}
Before con.commit(); the table has the max(ID)=3
After com.commit() the table has the max(ID)=4
But I obtain MAX(ID)=3
Can somebody help me to solve this?
You're doing it; if this is returning the wrong result either your DB doesn't contain what you think it contains, or your DB engine is broken (MySQL is often broken, possibly that's the problem. The fix is to not use mysql), or your code is broken. Your snippet contains an error (no semicolon after the first line), so this isn't a straight paste but a modification; generally you should paste precisely the code that is exhibiting the behaviour you don't understand, because if you edit it or try to simplify it without running the simplification, you may have accidentally removed the very thing that would explain what you're observing.
More generally, if all you want is the ID generated for an auto-increment column, this isn't how you do it. You can use statement's .getGeneratedKeys() method to get at these; you may have to pass in Statement.RETURN_GENERATED_KEYS as part of your executeUpdate call.
You do not need a PreparedStatement if you do not have a parametrized query. I would use Statement in this case.
You do not need while (rs.next()) as your query will return a single value. I would use if (rs.next()).
Your query does not have a field called ID and therefore rs.getString("ID") will throw SQLException. You should use rs.getString(1) or use an alias (e.g. maxId in the example shown below) in the query. Also, you should use getInt instead of getString.
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery("SELECT MAX(ID) AS maxId FROM MY_TABLE");
int id = Integer.MIN_VALUE;
if (rs.next()) {
id = rs.getInt(1);
//id = rs.getInt("maxId");
}
System.out.println(id);
This question already has answers here:
Java PreparedStatement complaining about SQL syntax on execute()
(6 answers)
Closed 6 years ago.
This is a really weird error that only started appearing today. When I use a prepared statement with ? for parameters, I get an error, but when I use it without parameters, it works just fine.
Here is the error-causing code:
String table = "files";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement prep = conn.prepareStatement("SELECT * FROM ?");
prep.setString(1, table);
ResultSet rs = prep.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("file_name"));
}
This produces the following error:
Exception in thread "main" 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 ''files'' at line 1
Also, changing it to the following works just fine:
String table = "files";
Connection conn = DriverManager.getConnection(DB_URL, DB_USER, DB_PASS);
PreparedStatement prep = conn.prepareStatement("SELECT * FROM " + table);
ResultSet rs = prep.executeQuery();
while(rs.next()) {
System.out.println(rs.getString("file_name"));
}
This doesn't seem to be making a whole lot of sense. Any ideas?
Tried it on another table and got more weired results.
This works and logs the admin in correctly:
String sql = "SELECT * FROM " + ADMIN_AUTH_TABLE + " WHERE " + column + " = '" + hashedPassword + "'";
PreparedStatement prepared = connection.prepareStatement(sql);
The following doesn't cause errors, but returns a message saying that the password entered is incorrect (it's correct - I double triple checked).
String sql = "SELECT * FROM " + ADMIN_AUTH_TABLE + " WHERE ? = ?";
PreparedStatement prepared = connection.prepareStatement(sql);
prepared.setString(1, column);
prepared.setString(2, hashedPassword);
Got it: use ? for values.
Also, the answer here helped.
Bind parameters cannot be used for identifiers in the SQL statement. Only values can supplied through bind placeholders.
This will work:
SELECT foo FROM bar WHERE id = ?
This will not work, because the table name is an identifier
SELECT foo FROM ? WHERE id = 2
You can't supply a column name, because column names are also identifiers.
A statement like this will run, but it may not do what you think it does.
SELECT ? AS foo FROM bar WHERE ? = 0
If we supply values of 'foo' for both placeholders, the query will actually be equivalent to a query containing two string literals:
SELECT 'foo' AS foo FROM bar WHERE 'foo' = 0
MySQL will run that statement, because it's a valid statement (if the table bar exists and we have privileges on it.) That query will return every row in bar (because the predicate in the WHERE clause evaluates to TRUE, independent of the contents of the table.. And we get returned the constant string foo.
It doesn't matter one whit that the string foo happens to match the name of column in our table.
This restriction has to do with how the SQL optimizer operates. We don't need to delve into all the details of the steps (briefly: parsing tokens, performing syntax check, performing semantics check, determining query plan, and then the actual execution of the query plan.)
So here's the short story: The values for bind parameters are supplied too late in that process. They are not supplied until that final step, the execution of the query plan.
The optimizer needs to know which tables and columns are being referenced at earlier stages... for the semantics check, and for developing a query plan. The tables and columns have to be identified to the optimizer. Bind placeholders are "unknowns" at the time the table names and column names are needed.
(That short story isn't entirely accurate; don't take all of that as gospel. But it does explain the reason that bind parameters can't be used for identifiers, like table names and column names.)
tl;dr
Given the particular statement you're running, the only value that can be passed in as a bind parameter would be the "hashedPassword" value. Everything else in that statement has to be in the SQL string.
For example, something like this would work:
String sqltext = "SELECT * FROM mytable WHERE mycolumn = ?";
PreparedStatement prepared = connection.prepareStatement(sqltext);
prepared.setString(1, hashedPassword);
To make other parts of the SQL statement "dynamic" (like the table name and column name) you'd have to handle that in the Java code (using string concatenation.) The contents of that string would need to end up like the contents of the sqltext string (in my example) when it's passed to the prepareStatement method.
The parameters of PreparedStatement should be applied only in parameters that can be used in conditional clauses. The table name is not the case here.
If you have a select where the table name can be applied in the conditional clause you can do it, otherwise you can not.
I'm using JTDS as a driver to connect to SQL server.
Here's the query that's giving me problems:
SELECT EmpID,FirstName,LastName,CompanyName,DepartmentName,JobTitle,HireDate FROM Employees where UPPER(FirstName) LIKE 'KEVIN%'
It returns 2 rows on SQL Server. One that has 'KEVIN' in upper case and another that has 'Kevin' like so. I used the wildcard to make sure I get both results. In my EmployeeDAO class I'm using the following:
ps = con.prepareStatement("SELECT EmpID,FirstName,LastName,CompanyName,"
+ "DepartmentName,JobTitle,HireDate FROM Employees WHERE UPPER(FirstName) LIKE ?");
ps.setString(1, FirstName + "%");
rs = ps.executeQuery();
And then of course I put KEVIN on my main. It only returns ONE row, which is the 'Kevin' row.
How do I fix this so it returns all rows?
Your query looks fine (although I would uppercase the parameter value before setting it, to make it more robust). The problem is just in the way how you're collecting the rows from the ResultSet. Likely you're plain overriding the previous row with the next row so that you end up with only one row (the last one) in your collection.
Default collation of the SQL Server installation is SQL_Latin1_General_CP1_CI_AS and it is not case sensitive.
Change collation of the query:
SELECT Col1
FROM Table1
WHERE Col1 COLLATE Latin1_General_CS_AS LIKE 'KEVIN%'
I'm having some small trouble trying to dynamically generate an SQL SELECT statement generated from an entry from a webpage.
Basically i have a small search engine in the website, it accepts three parameters (price,city,brand), so i have a JavaBean built in the same way with only 3 attributes, the same ones.
When performing a SELECT on the database i could make it this way using PreparedStatement
String sql=select * from product where price<=? and city=? and brand=?;
prep=conn.prepareStatement(sql);
prep.setDouble(1,price);
prep.setString(2,city);
prep.setString(3,brand);
where prep is of course a PreparedStatement obj
My problem comes when the user does not insert a parameter in the field of the web page, because apparently he is not interested on a limitation.
I need to find a way to "cut" the entry at runtime, like:
city field=""? then take out city from the search criteria:
String sql=select * from product where price<=? and brand=?;
One way i could do that is filling in the code in the servlet with else-if but thats not the only solution i'm sure.
Another potential solution would be to use IFNULL(expr1,expr2) function of SQL but in case is null, then i should just remove the null-field from the query.
Do you have any advice?
i hope its clear enough the way i explained it.
You can use OR in your WHERE clause to do something like:
WHERE (Price<=? OR ? IS NULL)
AND (City = ? OR ? IS NULL)
AND (Brand = ? OR ? IS NULL)
Try to replace condition "=" with Like '%[input_value]%'. In this way if uset left blank field you don't have any restriction.
You can use like for strings.
String sql = "SELECT * FROM product WHERE price <= ? AND city like '?' AND brand like '?'";
prep = conn.prepareStatement(sql);
prep.setDouble(1, price);
prep.setString(2, city);
prep.setString(3, brand);
See Exact match with sql like and the bind
And in case city/brand is not selected, then set it
prep.setString(2, "%");
prep.setString(3, "%");
If price is not selected, then use some very big number.
Excerpt from code
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sch.tab1 where col1 like lower ( 'ABZ' ) ");
preparedStatement.executeQuery();
The above code executes successfully.
But when i try to execute this
PreparedStatement preparedStatement = connection.prepareStatement("SELECT * FROM sch.tab1 where col1 like lower ( ? ) ");
preparedStatement.setString ( myValue );
preparedStatement.executeQuery();
It throws an exception."STRING TO BE PREPARED CONTAINS INVALID USE OF PARAMETER MARKERS"
What could be the problem here?
Answer found, see the comments
I suspect the problem is that you can't apply functions directly to parameters. Is there any particular reason why you want the lower casing to be performed at the database rather than in your code? (I can think of some potential reasons, admittedly.) Unless you really need to do this, I'd just change the SQL to:
SELECT * FROM sch.tab1 where col1 like ?
and call toLower() in Java, preferably specifying the appropriate locale in which to perform the lower-casing.
I think Carlos is on to something. Try
SELECT * FROM sch.tab1 where col1 like lower ( '' + ? )
or whatever passes for string concatenation operator in your version of SQL. Forcing a string context might get you past the error. May require extra parentheses.
For reference: I ran into the same problem while using the NORMALIZE_STRING function:
SELECT NORMALIZE_STRING(?, NFKD) FROM sysibm.sysdummy1
Error message:
THE DATA TYPE, LENGTH, OR VALUE OF ARGUMENT 1 OF NORMALIZE_STRING IS INVALID. SQLCODE=-171, SQLSTATE=42815, DRIVER=4.13.111
Using the following statement solved the problem (CONCAT). Thanks to Paul Chernoch!
SELECT search_normalize(NORMALIZE_STRING(? CONCAT G'', NFKD)) FROM sysibm.sysdummy1
Note the "G" prefix for Unicode compatibility.