Invalid Identifier when using LIKE query in Java - java

I'm trying to execute a LIKE query in Java using prepared statements but I'm getting the following error
ORA-00904: "%12P1A%": invalid identifier
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
connection = DataSourceFactory.getConnection();
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, "%12P1A%");
resultSet = statement.executeQuery();
//....
}catch (SQLException e) {
throw new DAOException(e.getMessage());
} finally {
DaoUtil.closeAll(connection, statement, resultSet);
}
May I know why is this incorrect?
For further Information, I'm actually getting '%12P1A%' by some other function so the code is something like
statement = connection.prepareStatement("select * from users where userID like ?");
statement.setString(1, getValue());
the query parses to something like
select * from users where userID like '%12P1A%'
but it is throwing MISSING IN or OUT Paramter. Idk why it is not picking the value. Any suggestions?

You could extract the value between '% and %' that you are getting from the input and then create your query as -
statement = connection.prepareStatement("select * from users where userID like '%" + <value-from-some-other-method> + "%'");
If there is an option, ask the method response to be the value directly instead of having it formatted for query parameter.

Related

Select * From java with preparedStatement [duplicate]

This question already has answers here:
Java MYSQL Prepared Statement Error: Check syntax to use near '?' at line 1
(2 answers)
Closed 1 year ago.
I faced this problem today with my select SQL. This method is supposed to show data from database in tex tfields. I changed it from statement to preparedStatement, but I faced a problem.
public Entreprise loadDataModify(String id) {
Entreprise e = new Entreprise();
PreparedStatement stmt;
try {
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery(sql);
while (rst.next()) {
stmt.setString(2, e.getNom());
stmt.setString(3, e.getEmail());
stmt.setString(4, e.getTel());
stmt.setString(5, e.getOffre());
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return e;
}
It shows i have problem with syntax and the output is " nu
You're calling the wrong method. Unlike Statement, when you're using a PreperedStatement you should first set the values for the parameters, and after you can call on that instance executeQuery() method.
Also, it's a best practice to use try-with-resources, because a Statement or PreparedStament object is a Resource (a resource is a class that implements AutoCloseable interface) and you have to close it. Using try-with-resources, it's done automatically.
The ResultSet instance is also a resource, but it's closed when the statement object is closed, so you don't have to close it explicitly.
So, the best way to solve your problem will be:
String selectAllByMail = "SELECT * FROM user WHERE mail=?";
try (PreparedStatement prpStatement = connection.prepareStatement(selectAllByMail)) {
// use prpStatement
prpStatement.setString(1, id);
ResultSet resultSet = prpStatement.executeQuery();
while (resultSet.next()) {
// process resultSet
}
} catch (SQLException throwables) {
throwables.printStackTrace();
}
You are not filling your Enterprise object. And you are not using executeQuery() function correctly. As seen below, the parameter inside the brackets has been removed. PreparedStatements first of all need the values of the parameters (your ? in the query) and then the formed query has to be executed. If you give a String parameter to executeQuery() then the query in the brackets will be executed.
And the part where Enterprise is being filled could be seen below.
This would be the correct way:
public Entreprise loadDataModify(String id) {
Entreprise e = new Entreprise();
PreparedStatement stmt;
try {
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery();
while (rst.next())
{
// rst keeps the data, so you have to traverse it and get the data from it in this way.
e.setNom( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setEmail( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setTel( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
e.setOffre( rst.getString("HERE EITHER THE COLUMN NAME OR INDEX"));
}
} catch (SQLException ex) {
System.out.println(ex.getMessage());
}
return e;
}
Your call to executeQuery() should not be passing the query string. Use this version:
String sql = "SELECT * FROM user WHERE mail=?";
stmt = cnx.prepareStatement(sql);
stmt.setString(1, id);
ResultSet rst = stmt.executeQuery();
while (rst.next()) {
// process result set
}
Your current code is actually calling some overloaded Statement#executeQuery() method, which is not the version of the method which you want to be calling.

How to select data from table with parameter

Trying to get all the data in the row with the specified name string. Im getting a syntax error right now. myConn is declared in the constructor and name is a varchar in the database named organization. My error code is "Can not issue executeUpdate() or executeLargeUpdate() for SELECTs"
public void getOrgByName(String name){
try {
st = myConn.createStatement();
String query = "SELECT * FROM organization WHERE name = ?";
PreparedStatement preparedStmt = myConn.prepareStatement(query);
preparedStmt.setString(1, name);
preparedStmt.executeUpdate();
}catch(Exception e){
System.out.println("Cannot get org name" + e);
}
}
You’re performing a select query so you’ll need to use executeQuery i.e
Replace this:
preparedStmt.executeUpdate();
With this:
ResultSet rs = preparedStmt.executeQuery();

Why does this Query return NULL?

I have a derby users database which I query, when the user clicks login on the application.
However, when I query the users table with the parameter [user] derby returns a null Object instead of the record it ought to return.
Here is my code:
String ssql = "SELECT * FROM USERS WHERE UNAME LIKE ?";
try{
DriverManager.registerDriver(new org.apache.derby.jdbc.EmbeddedDriver());
con = DriverManager.getConnection(url);
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
try{
while (rs.next()) {
if(rs.getString("PW").toCharArray().equals(txt_password.getPassword())){
sql.close();
con.close();
return true;
}
} catch (NPE ...) {...}
}
I tried it multiple times wit a test user with both the pw and the username set to "test"; but I always get the same error.
Why is the recordset always Null?
Thanks for your help :)
The documentation says
ResultSet getGeneratedKeys() throws SQLException
Retrieves any auto-generated keys created as a result of executing this Statement
object.
If this Statement object did not generate any keys, an empty
ResultSet object is returned.
Your select statement isn't generating any keys that's why it's returning an empty ResultSet. You aren't inserting anything hence no keys are being generated.
You can try ResultSet rs = sql.executeQuery();. It should work.
You are using it in wrong way.
The generated keys concept should be used only in the case DML of insert type query but not in the case of select query.
select simply select the rows from the table. In this case there is no chance of any keys getting generated.
In the case of insert query if any column is configured as auto increment or kind of functionality then some keys will get generated. These keys can be caught using Statement.RETURN_GENERATED_KEYS in java.
As you are using select query there is no need of using Statement.RETURN_GENERATED_KEYS.
You just modify below lines and everything will be fine.
sql = con.prepareStatement(ssql, Statement.RETURN_GENERATED_KEYS);
sql.setString(1, cbox_chooseUser.getSelectedItem().toString());
sql.executeQuery();
ResultSet rs = sql.getGeneratedKeys();
with
sql = con.prepareStatement( ssql );
sql.setString( 1, cbox_chooseUser.getSelectedItem().toString() );
ResultSet rs = sql.executeQuery();

Update sql statement in servlet not in servlet

I am trying to allow the user to change the password if he enters the right username. The username is drawn from the database and compared to the username the user enter in a form. My problem is after the validation is done the UPDATE statement is not producing any result. Can someone help me out please?
String un = request.getParameter("username");
String psw = request.getParameter("password");
String cPsw = request.getParameter("cpassword");
Connection con = ConnectionHelper.getConnection();
try {
ResultSet rs = userList(con);
if (rs.next()) {
String n = rs.getString("username");
if (n.equals(un)) {
out.print("Password match");
String updateQuery = "UPDATE RegisteredUserInfo SET password ='"
+ cPsw + "'WHERE username ='" + un + "'";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.executeQuery();
ServletContext context = getServletContext();
RequestDispatcher rd = context
.getRequestDispatcher("/Welcome.jsp");
rd.forward(request, response);
}
}
} catch (SQLException sx) {
out.println();
}
}
public ResultSet userList(Connection con) throws SQLException {
PreparedStatement ps;
ResultSet rs;
String matchingUname = "SELECT username FROM RegisteredUserInfo";
ps = con.prepareStatement(matchingUname);
rs = ps.executeQuery();
return rs;`
Try with ps1.execute(); or ps1.executeUpdate() instead of ps1.executeQuery();
Call con.commit(); to commit the changes and Don't forget to close the resources in the end.
Check the return type of below methods to make sure that data is inserted properly.
ResultSet executeQuery()
Executes the SQL query in this PreparedStatement object and returns the ResultSet object generated by the query.
int executeUpdate()
Executes the SQL statement in this PreparedStatement object, which must be an SQL INSERT, UPDATE or DELETE statement; or an SQL statement that returns nothing, such as a DDL statement.
Ream more about Difference between execute, executeQuery, executeUpdate
Points to Remember
Use PreparedStatement instead of using single quoted query string that may cause issue. Find a sample on Using Prepared Statements
Don't forget to close the resources such as connection, result set and statement.
Use finally block to handle it or Read more about Java7 -The try-with-resources Statement
Don't simply eat the exception in catch block. Do proper handling of the exception. You can try with e.printStackTrace() while development.
You need to call executeUpdate() for SQL UPDATE (or INSERT/DELETE).
String updateQuery = "UPDATE RegisteredUserInfo SET password = ?"
+ " WHERE username = ?";
PreparedStatement ps1 = con.prepareStatement(updateQuery);
ps1.setString(1, cPsw);
ps1.setString(2, un);
ps1.executeUpdate();
Also use the PreparedStatement as above. Look for SQL Injection, also escapes '.

SQL command from eclipse using JDBC

I have been searching and trying different stuff for awhile, but have not found an answer. I'm trying to make a connection to sql using JDBC from eclipse. I am having trouble when I need to select a string in the database. If I use:
Select name from data where title = 'mr';
That works with terminal/command line but when I try to use eclipse where I use
statement sp = connection.createstatement();
resultset rs = sp.executequery("select name from data where title = '" + "mr" + "'");
It does not give me anything while the terminal input does. What did I do wrong in the eclipse? Thanks
Heres a part of the code. Sorry, its a bit messy, been trying different things.
private boolean loginChecker(String cid, String password) throws SQLException{
boolean check = false;
PreparedStatement pstatment = null;
Statement stmt = null;
//String query = "SELECT 'cat' FROM customer";
String query = "select '"+cid+"' from customer where password = '"+password+"'";
try {
System.out.println("in try......");
//stmt = con.createStatement();
//ResultSet rs = stmt.executeQuery(query);
PreparedStatement prepStmt = con.prepareStatement(query);
ResultSet rs = prepStmt.executeQuery();
//System.out.print(rs.getString("cid"));
while(rs.next()){
check = true;
System.out.print(rs.getString("cid"));
}
} catch (SQLException e ) {
e.printStackTrace();
} finally {
if (stmt != null) {
//stmt.close();
}
}
return check;
}
Second try on a simpler query:
public List<Object> showTable() {
List<Object> result = new ArrayList<Object>();
String name = "bob";
try
{
PreparedStatement preStatement = con.prepareStatement("select total from test where name = ?");
preStatement.setString(1, name);
ResultSet rs1 = preStatement.executeQuery();
while(rs1.next()){
System.out.println("there");
System.out.println(rs1.getInt("total"));
}
}
catch (SQLException ex)
{
System.out.print("Message: " + ex.getMessage());
}
return result;
}
Remove the quotes around the column name.
String query = "select "+cid+" from customer where password = '"+password+"'";
You've not mentioned which database you're working with but many databases like Oracle change the column case to upper case unless they're quoted. So, you only quote table columns if that's how you had created them. For example, if you had created a table like
CREATE TABLE some_table ( 'DoNotChangeToUpperCase' VARCHAR2 );
Then you would have to select the column with quotes as well
SELECT 'DoNotChangeToUpperCase' FROM some_table
But, if you didn't create the table using quotes you shouldn't be using them with your SELECTs either.
Make sure you are not closing the ResultSet before you are trying to use it. This can happen when you return a ResultSet and try to use it elsewhere. If you want to return the data like this, use CachedRowSet:
CachedRowSet crs = new CachedRowSetImpl();
crs.populate(ResultSet);
CachedRowSet is "special in that it can operate without being connected to its data source, that is, it is a disconnected RowSet object"
Edit: Saw you posted code so I thought I add some thoughts. If that is your ACTUAL code than the reason you are not getting anything is because the query is probably not returning anything.
String query = "select '"+cid+"' from customer where password = '"+password+"'";
This is wrong, for two reasons. 1) If you are using prepared statements you should replace all input with '?' so it should look like the following:
String query = "select name from customer where password = ?";
Then:
PreparedStatement prepStmt = con.prepareStatement(query);
prepStmt.setString(1, password);
ResultSet rs = prepStmt.executeQuery();
2)
System.out.print(rs.getString("cid"));
Here are are trying to get the column named "cid", when it should be the name stored in cid. You should actually never be letting the user decide what columns to get, this should be hardcoded in.

Categories