PreparedStatement MySQLSyntaxErrorException using valid query string [duplicate] - java

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();

Related

How to Fix MySQL Count Function Error In Java? [duplicate]

This question already has answers here:
How to use a tablename variable for a java prepared statement insert [duplicate]
(4 answers)
Closed 6 months ago.
I am trying to create a method that will count the number of records I have in a certain table when the method is called. But for some reason, I keep getting an error saying I have a problem in my SQL code. Looking over everything, I couldn't find the problem. I even went as far to as to copy parts of another person's solution online, but this failed too. To better show where the error seems to be ocurring, I inserted two print statements in the code. I think Java and SQL must hate me! Any help would be most appreciated.
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM ?";
try(Connection conn = letConnect(); PreparedStatement ps = conn.prepareStatement(sql)){
ps.setString(1, tableName);
System.out.println("test");
ResultSet rs = ps.executeQuery();//error ocurrs here
//when the SQL code is executed
System.out.println("test");
num = rs.getInt("total");
} catch (SQLException e) {
e.printStackTrace();
}
return num;
}
Output:
test
java.sql.SQLSyntaxErrorException: 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 ''Country'' at line 1
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLError.createSQLException(SQLError.java:120)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.exceptions.SQLExceptionsMapping.translateException(SQLExceptionsMapping.java:122)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeInternal(ClientPreparedStatement.java:916)
at mysql.connector.java#8.0.30/com.mysql.cj.jdbc.ClientPreparedStatement.executeQuery(ClientPreparedStatement.java:972)
at Database_Interactor.tableCounter(Database_Interactor.java:25)
at MainClass.main(MainClass.java:10)
Based on the answer given above, the code should look something like this:
int tableCounter(String tableName) {
int num = 0;
String sql = "SELECT COUNT(*) AS total FROM "+ tableName;
Connection conn = letConnect();
try{Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql);
while (rs.next()){
num = rs.getInt("total");}
}catch (SQLException e) {
e.printStackTrace();}
return num;}

Why is my result set in java reading my dbeaver column for date as null and how can I work around this? [duplicate]

This question already has answers here:
Insert & fetch java.time.LocalDate objects to/from an SQL database such as H2
(1 answer)
Getting the date from a ResultSet for use with java.time classes
(3 answers)
Closed 3 years ago.
Why is my result set in Java reading my DBeaver column for date as null and how can I work around this?
Below you can see photos showing that Java is reading my date column from DBeaver as null when that is not the case, as well as my prepared statement and result set in Java.
public Set<Reimbursement> getReimbursementsForEmployee(Employee employee) {
Connection conn = ConnectionUtil.getConnection();
String sql = "SELECT * FROM reimbursement WHERE e_id = ?";
Set<Reimbursement> reimbursements = new HashSet<Reimbursement>();
try {
PreparedStatement ps = conn.prepareStatement(sql);
ps.setInt(1, employee.getEmployeeId());
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Reimbursement reimbursement = new Reimbursement();
reimbursement.setReimbursementNumber(rs.getInt("reimbursementnumber"));
reimbursement.setDate(rs.getDate("ddate"));
reimbursement.setAmount(rs.getDouble("amount"));
reimbursement.setReimbursementRequestInfo(rs.getString("reimbursementrequestinfo"));
reimbursement.setManagerComment(rs.getString("managercomment"));
reimbursement.setStatus(rs.getString("status"));
reimbursement.setEmployeeId(rs.getInt("e_id"));
reimbursement.setManagerId(rs.getInt("m_id"));
reimbursements.add(reimbursement);
}
return reimbursements;
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}

Getting wrong output in PreparedStatement [duplicate]

This question already has answers here:
mysql prepared statement error: MySQLSyntaxErrorException
(2 answers)
Closed 6 years ago.
I've a course table with the columns,
id, teacher_id and name.
This is the method that I'm using to get a course by id.
public static Course getById(int id) throws SQLException {
String query = "SELECT * FROM courses WHERE id = ?" ;
Course course = new Course();
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
try{
DriverManager.registerDriver(new com.mysql.jdbc.Driver ());
connection = (Connection) DriverManager.getConnection(ConnectDb.CONN_STRING, ConnectDb.USERNAME, ConnectDb.PASSWORD);
statement = (PreparedStatement) connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE,
ResultSet.CONCUR_READ_ONLY);
statement.setInt(1, id);
resultSet = statement.executeQuery(query);
while (resultSet.next()) {
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setTeacherId(resultSet.getInt("teacher_id"));
}
}catch (SQLException e) {
System.err.println(e);
}finally{
if (resultSet != null) resultSet.close();;
if (statement != null) statement.close();
if(connection != null) connection.close();
}
return course;
}// end of method
When I run this method, I get an output id :0, teacher_id : 0
The server log says that I've an SQLException
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
The bug is here:
resultSet = statement.executeQuery(query);
You're not calling PreparedStatement#executeQuery, you're calling Statement#executeQuery (Statement is a superinterface of PreparedStatement). So the parameter substitution isn't happening and you're actually sending that ? to the server.
Change it to:
resultSet = statement.executeQuery();
// No argument here ---------------^
(And yes, this is an API design flaw; and no, you're not the first to fall into it.)
There are a few other things about that code that could use improvement:
You're always returning a Course, even if an exception occurred. Best practices would be to allow the exception to propagate to the caller; second-best practices would be to return some kind of flag to the caller that an error occurred, such as null.
The try-with-resources statement can make that code both shorter and clearer
You shouldn't have to cast the return values of getConnection or prepareStatement.
You're using while, but you're expecting only a single result. if would make more sense.
On that topic, you can give the driver a hint in that regard by using setMaxRows.
Your method declares that it can throw SQLException, which is literally true since it calls close, but the only useful SQLException is actually being caught, logged, and suppressed by the code, making declaring it on the method a bit misleading.
I'm told modern JDBC drivers don't need the registerDriver call anymore. (I personally haven't used JDBC for a while now, so...)
Here's an example incoporating the above. It allows an exception to propagate, so errors (exceptional conditions) are not handled in the normal flow of code; it returns null if there's no matching course:
public static Course getById(int id) throws SQLException {
String query = "SELECT * FROM courses WHERE id = ?";
try (
Connection connection = DriverManager.getConnection(ConnectDb.CONN_STRING, ConnectDb.USERNAME, ConnectDb.PASSWORD);
PreparedStatement statement = connection.prepareStatement(query, ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_READ_ONLY);
) {
statement.setInt(1, id);
statement.setMaxRows(1);
try (
ResultSet resultSet = statement.executeQuery();
) {
if (resultSet.next()) {
Course course = new Course();
course.setId(resultSet.getInt("id"));
course.setName(resultSet.getString("name"));
course.setTeacherId(resultSet.getInt("teacher_id"));
return course;
}
// No matching course
return null;
}
}
} // end of method
That can probably be improved further, but you get the idea.

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

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);

Query works on phpMyAdmin, but not in Java [duplicate]

This question already has answers here:
SQL query works in phpMyAdmin but not in JDBC [closed]
(2 answers)
Closed 9 years ago.
I'm using MySQL and JDBC to the database for a site in JSP.
I generate an SQL query for a search command, the query works when I run it manually on phpMyAdmin and it return 1 row match.
But after executing my query the ResultSet is empty (I can't get the values of the table).
This is the code that executes the query:
public static Product findLikeProd(String ProductName)
{
Product Product = null;
try
{
ResultSet rs = Database.executeSelect1("SELECT * FROM products WHERE prodName LIKE '%"+ProductName+"%' AND exist=1");
if (rs.next())
{
Product = new Product(rs.getInt("PKid"), rs.getString("prodName"), rs.getString("description"), rs.getDouble("price"), rs.getInt("deliveryTime"), rs.getString("imgUrl"));
}
//Database.closeCon();
}
catch (SQLException e)
{
e.printStackTrace();
}
return Product;
}
A query for example:
SELECT * FROM Products WHERE prodName LIKE '%מהיר%' AND exist=1
The code:
public synchronized static ResultSet executeSelect1(String sqlCmd) {
ResultSet rs = null;
try {
MysqlDataSource ds = new MysqlConnectionPoolDataSource();
ds.setServerName("localhost");
ds.setDatabaseName("tarazJsp");
con=ds.getConnection("root","");
Statement st = con.createStatement();
rs = st.executeQuery(sqlCmd); //The problem is here. rs is received(!=null) but I can't get his parameters.(empty)
} catch (SQLException e) {
e.printStackTrace();
}
return rs;
}
When I try to get the string from rs, it throws an SQLException.
How should I fix it?
You're not setting the MySQL connection encoding, so the default encoding will be used. The default encoding is likely latin1, which doesn't include Hebrew characters. This means that the SQL MySQL will actually execute will be more like ... WHERE prodName LIKE '%????%' ... and that's not returning any results.
A possible fix is setting an encoding that does support Hebrew, like utf8:
ds.setServerName("localhost");
ds.setEncoding("utf8");

Categories