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.
Related
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.
This question already has answers here:
MySQLSyntaxErrorException near "?" when trying to execute PreparedStatement
(2 answers)
Closed 4 years ago.
I am trying to execute the following code
package jdbclesson;
import java.sql.*;
public class PreparedQuery {
public static void main(String[] args) throws Exception
{
String url = "jdbc:mysql://localhost:3306/alien?useSSL=false";
String uname = "root";
String pass = "ma123";
String query = "UPDATE student SET username= ? where userid= ? ";
PreparedStatement stmt = null;
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(url, uname, pass);
stmt = con.prepareStatement(query);
stmt.setString(1, "tina");
stmt.setInt(2, 6);
int rs = stmt.executeUpdate(query);
System.out.println(rs);
stmt.close();
con.close();
}
}
but getting following errors
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 '? where
userid=?' at line 1
My database has only 1 table student with 2 columns userid and username and 10 rows what m i missing
Try:
int rs = stmt.executeUpdate();
Instead of:
int rs = stmt.executeUpdate(query);
executeUpdate() runs the query of the prepared statement, which is what you want. executeUpdate(query) runs the query passed to the method. You were getting the error because you were passing an SQL with errors (contains ?).
Please try:
"UPDATE student SET username= ? ” + ” where userid= ?";
int rs=stmt.executeUpdate();
My code looks as follows:
ResulSet rs = stmt.executeQuery("select passwd from mrs_user where email="+mail_id);
String usr_paswd = rs.getString(1);
But the error is as follows:
java.sql.SQLException: ORA-04054: database link G.COM does not exist
mail_id=dk#g.com
First, String should be between to quotes 'mail_id', but this way is not secure it can cause SQL Injection or syntax error instead you can use PreparedStatement.
Second, you still not get any result, you have to call rs.next() before to moves the cursor to the next row (read about Retrieving and Modifying Values from Result Sets).
Code example
String usr_paswd = null;
try (PreparedStatement stmt = connection.prepareStatement(
"select passwd from mrs_user where email=?")) {
stmt.setString(1, mail_id);
ResulSet rs = stmt.executeQuery();
if(rs.next()){
usr_paswd = rs.getString(1);
}
}
Why do I get this error :
Error :java.sql.SQLException: ResultSet closed
from this code:
try{
ArrayList<String> longArray = new ArrayList<String>();
longArray.add("12345678912"); // All column in sqlite database are "text" so that's why I create String List
longArray.add("12345678911");
System.out.println(longArray);
String parameters = StringUtils.join(longArray.iterator(),",");
connection = sqliteConnection.dbConnector();
PreparedStatement pst=connection.prepareStatement("select columnA from TableUser where id in (?)");
pst.setString(1, parameters );
ResultSet rs = pst.executeQuery();
System.out.println(rs.getString("columnA")); // did not print anything, probably rs is empty
rs.close();
Database details:
I have a table TableUser in database where there is a column "id" as Text.
Another question : Is value in database 12345678912 (TEXT) the same as longArray.add("12345678912")?
You're missing an if(rs.next()) or while(rs.next()) after you retrieve the ResultSet.
For your other question...yes, they're both Strings aren't they?
Edit:
The problem was essentially trying to put multiple parameters into the IN statement in a PreparedStatement. See PreparedStatement IN Clause Alternatives
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);