What's wrong with my JDBC select prepared statement? [duplicate] - java

This question already has answers here:
right syntax to use near '?'
(3 answers)
Closed 7 years ago.
I'm trying to debug my prepared statement in java and I'm stuck on this checkEmail function that I implemented. When I go into debugging and it reaches the setString line, it shows NOT SPECIFIED in place of the '?'. If I hardcode 'findEmail' into the String query it will work and find the email. Here is the piece of code:
public static boolean checkEmail(String findEmail) {
Connection conn = EstablishConnection.conn;
boolean found = false;
try {
String query = "SELECT email FROM customers WHERE email=?";
Logging.debug(query);
PreparedStatement preparedStatement = conn.prepareStatement(query);
preparedStatement.setString(1,findEmail);
ResultSet rs = preparedStatement.executeQuery(query);
//Iterate through the results of the query
if (rs.next()) {
found = true;
}
preparedStatement.close();
} catch (Exception e) {
Logging.debug("Exception thrown in CustomerOperations.getCustomerInfo(): " + e.getMessage());
e.printStackTrace();
}
return found;
}

Try to replace this :
ResultSet rs = preparedStatement.executeQuery(query);
With:
ResultSet rs = preparedStatement.executeQuery();
Because you had already pass the query to prepareStatement : conn.prepareStatement(query);

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.

Using Java and Mysql getting exception com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 6 years ago.
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 getting this exception
private String selectCustDetail= "SELECT NAME, PASSWORD, RESID, ACTIVATED, USERTYPE FROM USERDETAIL WHERE MOBILENO=?";
ResultSet rs;
//PreparedStatement preparedStatement = null;
PreparedStatement preparedStatement = null ;
try {
// preparedStatement = con.prepareStatement(selectCustDetail);
preparedStatement = con.prepareStatement(selectCustDetail);
preparedStatement.setString(1, mobileno.toString().trim());
rs = preparedStatement.executeQuery(selectCustDetail );
while (rs.next()) {
// LOGGER.info("fetching - 1" + mobileno);
System.out.println(rs.getString("name"));
userDetai.setName(rs.getString("name"));
userDetai.setPassword(rs.getString("password"));
userDetai.setRestaurant(rs.getString("resId"));
userDetai.setActivated(rs.getString("activated"));
userDetai.setType(rs.getString("userType"));
// LOGGER.info("fetching - 2" + userDetai.getActivated());
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
//LOGGER.info("Exception - " + e.getMessage());
dinepostcons.msg = dinepostcons.dbError;
return false;
}
finally
{try {
if (preparedStatement != null) {
preparedStatement.close();
}
Change
rs = preparedStatement.executeQuery(selectCustDetail );
to
rs = preparedStatement.executeQuery();
You want the method that invokes your preparedStatement with bind parameters. Not the method from Statement that takes a String without bind parameters.

Reusing PreparedStatement causes SQLException [duplicate]

This question already has an answer here:
java.sql.SQLException: Operation not allowed after ResultSet closed MySQL Java [duplicate]
(1 answer)
Closed 6 years ago.
Try with recources gives me following exception:
java.sql.SQLException: Operation not allowed after ResultSet closed
My code:
public Set<Tablet> viewAllTablets(int offset, int noOfRecords) throws OutOfRangeException {
Set<Tablet> tabletSet = new HashSet<>();
Tablet tablet = null;
try(Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT SQL_CALC_FOUND_ROWS * FROM tablets limit " + offset + ", " + noOfRecords + ";");
ResultSet resultSet = preparedStatement.executeQuery();
ResultSet resultSet1 = preparedStatement.executeQuery("SELECT FOUND_ROWS()");){
while (resultSet.next()){
tablet = new Tablet();
tablet.setTabletId(resultSet.getInt("idTablet"));
tablet.setName(resultSet.getString("name"));
tablet.setNeedRecepie(resultSet.getBoolean("need_recipe"));
tablet.setPrice(resultSet.getDouble("price"));
tablet.setTypeId(resultSet.getInt("type_id"));
tablet.setDescription(resultSet.getString("description"));
tablet.setTabletType(TypeFactory.getType(tablet.getTypeId()));
tablet.setWeight(resultSet.getDouble("weight_of_pack"));
tablet.setPillsCount(resultSet.getInt("pills_count"));
tabletSet.add(tablet);
}
if(resultSet1.next())
this.noOfRecords = resultSet1.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}
return tabletSet;
}
Executing a second query on the PreparedStatement implicitly closes the ResultSet from the previous query. From Statement:
By default, only one ResultSet object per Statement object can be open at the same time.
Use two different statements, something along these lines (note how resultSet1 is retrieved) although of course I don't know what the requirements of your FOUND_ROWS function are:
try (
Connection connection = dataSource.getConnection();
PreparedStatement preparedStatement = connection.prepareStatement("SELECT SQL_CALC_FOUND_ROWS * FROM tablets limit " + offset + ", " + noOfRecords + ";");
ResultSet resultSet = preparedStatement.executeQuery();
ResultSet resultSet1 = connection.createStatement().executeQuery("SELECT FOUND_ROWS()"); // ****
) {
while (resultSet.next()) {
tablet = new Tablet();
tablet.setTabletId(resultSet.getInt("idTablet"));
tablet.setName(resultSet.getString("name"));
tablet.setNeedRecepie(resultSet.getBoolean("need_recipe"));
tablet.setPrice(resultSet.getDouble("price"));
tablet.setTypeId(resultSet.getInt("type_id"));
tablet.setDescription(resultSet.getString("description"));
tablet.setTabletType(TypeFactory.getType(tablet.getTypeId()));
tablet.setWeight(resultSet.getDouble("weight_of_pack"));
tablet.setPillsCount(resultSet.getInt("pills_count"));
tabletSet.add(tablet);
}
if (resultSet1.next())
this.noOfRecords = resultSet1.getInt(1);
} catch (SQLException e) {
e.printStackTrace();
}
Also: Don't use Statement's executeQuery(String) on PreparedStatement. It really shouldn't be there, it's a flaw in the java.sql package design. In fact, the documentation for Statement#executeQuery says:
Note:This method cannot be called on a PreparedStatement or CallableStatement.

PreparedStatement throws syntax error [duplicate]

This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 7 years ago.
Im preparing a query using PreparedStatements and it runs fine when i hardcode te query with the condition parameter.
but throws error , if the parameter is passed from setString() method.
com.mysql.jdbc.JDBC4PreparedStatement#2cf63e26: select * from linkedin_page_mess ages where company_id = '2414183' 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
In the error log, above my query looks fine.
public JSONObject getLinkedInMessages(String compId)
{
linlogger.log(Level.INFO, "Called getLinkedInMessages method");
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
JSONObject resObj = new JSONObject();
JSONArray tempArray = new JSONArray();
try
{
conn = InitOrGetConnection();
String query = "select * from linkedin_page_messages where company_id = ?";
PreparedStatement pst=conn.prepareStatement(query);
pst.setString(1, compId);
System.out.println("\n\n"+pst.toString());
rs= pst.executeQuery(query);
// process resultset logics
}
catch(Exception e)
{
System.out.println(e);
linlogger.log(Level.INFO, "Exception occured "+e.toString());
}
}
Is there anything wrong with the PreparedStatements?
Remove the parameter from
rs= pst.executeQuery(query);
change to
rs= pst.executeQuery();
If you pass query in pst.executeQuery(query); as parameter then this passed query string take priority over the query string you passed in conn.prepareStatement(query); and since in query(select * from linkedin_page_messages where company_id = ?) you dint pass parameter you get the error.
remove the parameter in this line:
rs= pst.executeQuery(query);
It must be
rs= pst.executeQuery();
Because the statement is prepared at PreparedStatement pst=conn.prepareStatement(query);
execute(String sql) is inherited from Statement and will execute the satement (sql) without prepared it.

PreparedStatement MySQLSyntaxErrorException using valid query string [duplicate]

This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 8 years ago.
I've spent hours looking at what seems like what should be perfectly working code. The connection.createStatement() version of this method works fine but as soon as I try to convert it over to the better, connection.prepareStatement() version it throws a MySQLSyntaxErrorException and complains about a problem near the '?' character in my query string. The code is posted below and I simply cannot see the problem with it. The database field is VARCHAR and accepts Strings so that is not the problem.
public Discussion getDbDiscussionInstance(String _instanceId) throws SQLException {
String qryStr = null;
PreparedStatement myStmt = null;
ResultSet myRs = null;
// Try to build the object with existing data.
try {
qryStr = "SELECT assignment_id, discussion_id, section_id, user_id, circle_id, breakout_id, title, description, created, due FROM macb_discussions WHERE instance_id=?";
myStmt = connection.prepareStatement(qryStr);
myStmt.setString(1, _instanceId);
myRs = myStmt.executeQuery(qryStr);
if (rs.next()) {
this.discussionId = myRs.getString("discussion_id");
}
} catch (SQLException e) {
dbFunc.catchSQLException(e);
} finally {
myRs.close();
myStmt.close();
}
}
Use only myStmt.executeQuery(); without the argument, you have already preperad the statement
From the docs,
Statement.executeQuery(String sql)
PreparedStatement.executeQuery()
So change your function accordingly.
myStmt = connection.prepareStatement(qryStr); to
myStmt = connection.prepareStatement();

Categories