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

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

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

SQL Lite Query (between in dates) doesn't work

in my small test program I have some SQL Queries. The first SELECT * FROM kilometer; works properly and returns all the columns in the table. So in Java embedded, ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer;"); returns an ResultSet which is not empty.
Now I wanted to get only the rows within a specific date. But my embedded query ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';"); returns an empty ResultSet. But I've tested it online and it worked properly. Where is my mistake? I've consulted already some pages like this, but I can't find the mistake.
I am using SQLite 3.15.1 and Java SE 8.
Full java code:
public ArrayList<Strecke> getErgebnisse(final String startzeitpunkt, final String zielzeitpunkt) {
ArrayList<Strecke> strecken = new ArrayList<>();
try {
try {
if (connection != null) {
}
connection = DriverManager.getConnection("jdbc:sqlite:" + DB_PATH);
if (!connection.isClosed())
} catch (SQLException e) {
throw new RuntimeException(e);
}
Statement stmt = connection.createStatement();
ResultSet rs = stmt.executeQuery("SELECT * FROM kilometer WHERE datum BETWEEN '2016-01-01' AND '2016-12-31';");
while (rs.next()) {
strecken.add(new Strecke(Instant.ofEpochMilli(rs.getDate("datum").getTime()).atZone(ZoneId.systemDefault()).toLocalDate(), rs.getString("startort"), rs.getString("zielort"), rs.getDouble("kilometer")));
}
rs.close();
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
return strecken;
}
First of all I would recommend that you use prepared statements while executing your queries instead of passing the query directly as a string......secondly I believe the problem here is that you are passing the date as a string in quotes and not a date.....I think that is the issue here. You would need to use sqllites datetime functions for this....

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