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

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

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.

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

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

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