Java skips else condition - java

I'm not sure why, but for some reason, the following code skips the else condition. I've tried just about everything I can think of, including switching the code blocks, but it still skips the else part. Basically, I want this method to return String temp = "no" if String docID that is passed to the method is not found in the FILESTATUS database, and String temp = "yes" if it is found.
static String checkDocID(String docID)
{
String temp = null;
System.out.println("Checking if data already exists in database...");
try
{
Main.stmt = Main.con.createStatement();
String command = "SELECT * FROM FILESTATUS WHERE ID='" + docID + "'";
ResultSet queryResult = Main.stmt.executeQuery(command);
if (!queryResult.next())
{
temp = "no";
}
else
{
while (queryResult.next())
{
String result = queryResult.getString("ID");
if (result.equals(docID))
{
temp = "yes";
break;
}
}
}
Main.stmt.close();
}
catch (Exception ex) {ex.printStackTrace();}
return temp;
}
Thanks!

Because you end up calling queryResult.next() in the "if" and again in the while, you're skipping the first result. If there is only one result, the while loop will never execute.
If I can make a couple of suggestions:
Use bound variables in a PreparedStatement rather than putting "docID" in the query string
Don't test result.equals(docID) since the query already assured that.
prefer boolean to String "yes" or "no"
set the result to "no" or false, then set it to "yes" or true in the loop. The extra assignment is probably faster than the extra test, plus you can skip the do{}while which most people find harder to read.

Might be better to restructure this loop as:
static String checkDocId(String docId) {
String temp = "no";
while (queryResult.next()) {
String result = queryResult.getString("ID");
if (result.equals(docID)) {
temp = "yes";
break;
}
}
return temp;
}
Some people don't like using break (I usually don't) so you can use a boolean in your while (I find that it reads more like english and you can tell the terminating condition right from the while instead of looking for an if inside):
static String checkDocId(String docId) {
boolean found = false;
while (queryResult.next() && !found) {
String result = queryResult.getString("ID");
found = result.equals(docID);
}
return found ? "yes" : "no";
}
You're performing a needless comparison otherwise. Remember, a while is just an if with a goto at the end ;)
As far as your problem is concerned, what Paul said is correct. Eitherway, I would still restructure the loop so that it's more elegant.

After a bit astonishment about the code (leaking DB resources, not trusting the DB that it returns the right docID, doing a SELECT * while you don't need all of the columns at all, not taking benefit of SQL-injection-sanitization powers of PreparedStatement, using String instead of boolean to denote a true/false value, a messy code flow), here's how it should really be done instead:
private static final String SQL_EXIST_DOCID =
"SELECT id FROM filestatus WHERE id = ?";
public boolean exist(String docID) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultSet = null;
boolean exist = false;
try {
connection = database.getConnection();
statement = connection.prepareStatement(SQL_EXIST_DOCID);
statement.setString(1, docID); // Shouldn't it be a Long instead? Characterbased PK's are *far* from efficient.
resultSet = statement.executeQuery();
exist = resultSet.next();
} finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (statement != null) try { statement.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return exist;
}
Clear, concise and simple as that. For more insights about using basic JDBC the right way you may find this article useful. I hope that you take it serious to learn from it. Really.

You are calling queryResult.next twice before you are trying to read it. To prove this, put a println or something right after the else (before the while).
Since you are selecting by a particular ID, moving to next() twice will in fact fail the second time (presumably) and never execute the while block.

rs.next() rolling current cursor after each call
try with
static String checkDocID(String docID)
{
String temp = null;
System.out.println("Checking if data already exists in database...");
try
{
Main.stmt = Main.con.createStatement();
String command = "SELECT * FROM FILESTATUS WHERE ID='" + docID + "'";
ResultSet queryResult = Main.stmt.executeQuery(command);
boolean found = queryResult.next();
if (!found)
{
temp = "no";
}
else
{
do {
String result = queryResult.getString("ID");
if (result.equals(docID))
{
temp = "yes";
break;
}
} while (queryResult.next())
}
Main.stmt.close();
}
catch (Exception ex) {ex.printStackTrace();}
return temp;
}

Related

Sql Exception Illegal operation on empty result set while it's working on My Sql Workbench

I wanted to make SQL operations easier with this class, but I am getting an exception indicating the result set is empty. The same query is working in MySQL workbench. I don't understand what the problem is.
import java.sql.*;
public class DataBase
{
private String user = "jsmith";
private String pass = "LetMeIn";
private String url = "jdbc:mysql://localhost:3306/java";
private String Schema, Table;
private Connection con;
private ResultSet Result;
private PreparedStatement pQuery;
public DataBase(String Database, String Table)
{
this.Schema = Database;
this.Table = Table;
}
private boolean createConnection()
{
boolean b = false;
try {
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(url, user, pass);
b = true;
} catch (Exception e) {
System.out.println("Connection Exception " + e.getMessage());
e.printStackTrace();
b = false;
}
return b;
}
public String getStringData(String Desireddata, String fromColumn, String condition)
{
boolean b = createConnection();
String retrivedString = "";
if (b != false && Schema != null && Table != null) {
try {
pQuery = con.prepareStatement("SELECT ? FROM " + Schema + "." + Table + " WHERE ? = ?");
pQuery.setString(1, Desireddata);
pQuery.setString(2, fromColumn);
pQuery.setString(3, condition);
Result = pQuery.executeQuery();
Result.next();
retrivedString = Result.getString(Desireddata);
} catch (Exception e) {
retrivedString = "False";
System.out.println(e.getMessage());
e.printStackTrace();
}
} else {
System.err.println("No Connection or Database not Defined ");
retrivedString = "False";
}
return retrivedString;
}
}
And the exception:
Illegal operation on empty result set.
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:1056)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:957)
at com.mysql.jdbc.SQLError.createSQLException(SQLError.java:927)
at com.mysql.jdbc.ResultSetImpl.checkRowPos(ResultSetImpl.java:817)
at com.mysql.jdbc.ResultSetImpl.getStringInternal(ResultSetImpl.java:5514)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5434)
at com.mysql.jdbc.ResultSetImpl.getString(ResultSetImpl.java:5474)
at sync.DataBase.getStringData(DataBase.java:44)
...
You have two issues:
You can't use parameter binding on object names, so doing SELECT ? FROM... is invalid.
You aren't checking the return value from ResultSet.next(). If it returns true there is data to be read, if it returns false there is no more data.
To fix the first problem, you would need to change your code from:
pQuery = con.prepareStatement("SELECT ? FROM ... WHERE ? = ?");
to:
pQuery = con.prepareStatement("SELECT " + Desireddata + " FROM ... WHERE " + fromColumn + " = ?");
But make sure that Desireddata and fromColumn are not derived directly from user input or you will be vulnerable to a SQL injection attack.
To fix the second problem, change:
Result.next();
retrivedString = Result.getString(Desireddata);
to:
while (Result.next()) { /* You COULD use 'if' instead */
retrivedString = Result.getString(Desireddata);
}
And although not a problem, stylistically you should not have instance variables that start with a capital letter. So instead of Result you should use result or resultSet or rs. Typically you would only use a capital letter as the first character if you were defining a new type (like a class or interface).
Your resultset Result is empty. So before processing, check whether Result is null or not.

How to check if deletion was successful in the database?

I wanted an error to popup, when the user entered a wrong id into the delete field. But even if a wrong id is entered, the query still proceeds, but no data is deleted. Here's my code:
String value = jTextField19.getText();
if (value == null || "".equals(value)) {
JOptionPane.showMessageDialog(null, "The field is blank!");
} else {
theQuery("DELETE FROM inventorydb WHERE item_id=('"+jTextField19.getText()+"') AND item_id IS NOT NULL");
}
The theQuery method:
private void theQuery(String query) {
Connection con = null;
Statement st = null;
try {
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/inventory", "root", "");
st = con.createStatement();
st.executeUpdate(query);
JOptionPane.showMessageDialog(null, "Done!");
} catch (Exception ex) {
JOptionPane.showMessageDialog(null,"Error!");
}
}
First of all: do not ever directly build SQL queries from user input, use prepared statements instead. If you don't know about SQL Injection, you should.
If you are using JDBC, you can check the result of #executeUpdate() to see how many rows were affected. If it was zero, then you can say that it was a wrong id.
This is the method definition:
public int executeUpdate(java.lang.String sql)
The return value is:
An int that indicates the number of rows affected, or 0 if using a DDL statement.
In the program at hand, you can just simply do this:
int deleted = st.executeUpdate(query);
if (deleted == 0) {
JOptionPane.showMessageDialog(null, "Nothing to delete!");
return;
}

Comparing user input to mysql database value

public void datuieguve(){
Scanner ievads = new Scanner(System.in);
String lietotIn = ievads.next();
// String paroleIn = ievads.next();
try {
quer = savien.createStatement();
String kverijs = "select lietotajvards from lietotaji where lietotajvards = '" +lietotIn+ "';";
rezult = quer.executeQuery(kverijs);
System.out.println(rezult.next());
String lietotajvards = rezult.getString("lietotajvards");
if (rezult.equals(lietotIn))
{
System.out.println("Yup");
}
else
{
System.out.println("Nope");
}
} catch(Exception ex) {
System.out.println("Kluuda: " +ex);
}
ievads.close();
}
Hi guys, I'm trying to create a code that will take user input and compare it with mysql database value. The problem is, it's not working and I'm stuck. I'd appreciate if someone could figure out what's wrong with my code and give me some tips or something, because I can't :)
I think I got down the connection part but the comparison is driving me nuts.
Make these changes on your code :
while(rezult.next()){
String lietotajvards = rezult.getString("lietotajvards");
if(lietotajvards.equals(lietotIn))
{
System.out.println("Yup");
}
...
}
Edit:
Its good practice to use prepared statement instead of create statement.
Ex:
Connection db = con.getConnection();
try {
PreparedStatement ps = ...;
try {
ResultSet rs = ...
try {
...
}
finally {
rs.close();
}
}
finally {
ps.close();
}
}
finally {
db.close();
}

compare integer text field value with mysql data in java

I want to check whether the newly entered data is already in the table
code:
txtNo = new JTextField();
{
try {
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select No from bank where No='"+txtNo.getText()+"' ");
int ch =rs1.getInt("No");
int ch4= Integer.parseInt(txtNo.getText());
if(ch==ch4) // input 58 == 58
System.out.println("already exits");
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
Error :
Exception:java.sql.SQLException: Illegal operation on empty result set.
You need to check if the result set has elements or not:
while(rs1.next())
{
int ch = rs1.getInt("No");
// ...
}
You get this exception when the select statement returns an empty set. Add a try/catch block which acts upon the knowledge that the data is not already in the table in the catch block.
You need to check the ResultSet first to check to see that it contains rows:
if (rs1.next()) {
int ch =rs1.getInt("No");
...
}
The easiest way to check whether a particular record exists in the database might be just as follows:
Select 1 from bank where No = [your_supplied_value]
This query would return 1 if it finds a row in your database with the supplied data or return an empty resultset. So, all you need to check is whether ANY value is returned in the resultset or whether it is emtpy.
Here's a sample code to get you started:
txtNo = new JTextField();
{
try {
String compareText = txtNo.getText().trim();
if(compareText.length() > 0){
Class.forName("com.mysql.jdbc.Driver");
String srcurl1 = "jdbc:mysql://localhost:3306/DB_name";
Connection con = DriverManager.getConnection(srcurl1,"root","paswrd");
Statement stmt1 = con.createStatement();
ResultSet rs1 = stmt1.executeQuery("select 1 from bank where No='"+txtNo.getText()+"' ");
boolean isPresent = rs1.next();
if(isPresent){
System.out.println("Already exists!!");
}
}
}
catch(Exception e)
{
System.out.println("Exception:"+e);
}
}
I hope this is not your final code, because there're several problems with it:
You're not managing your resources properly. Once you're done querying your database, you should consider closing your resultset, statement and connection objects.
Note that I checked whether the text in the JTextField is empty or not. This is a good way of preventing a call to the database when you know that the text field had no value in it.
I would suggest using a PreparedStatement rather than a Statement for querying to your database.
A ResultSet is initially positioned before the first row. So you need to call next() to move it to the next row (and check that it returns true) before you call one of the getXXX() methods.
JTextField input = new JTextField();
ArrayList < Integer > list = new ArrayList < Integer > ();
int integerv = Integer.parseInt(input.getText());
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/DB_name", "root", "yourpassword");
Statement stm = con.createStatement();
ResultSet rs = stm.executeQuery("select column_name from table_name");
while (rs.next()) {
list.add(rs.getInt(1));
}
for (int a = 0; a < list.Size(); a++) {
if (a.get(a) == integerv) {
System.out.println("Match found");
break;
} else {
System.out.println("Match not found");
break;
}
}
} catch (Exception e) {
System.out.println("Error :" + e.getMessage());
}

delete sql not deleting

I'm trying to delete an event from my table. However I can't seem to get it to work.
My SQL statement is:
public void deleteEvent(String eventName){
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
db.update(query);
System.out.println (query);
}
Using MySQL db
Try using the following :
String query = "DELETE FROM `Event` WHERE `eventName` ='"+eventName+"' LIMIT 1";
try {
Connection con = getConnection();
Statement s = con.createStatement();
s.execute(query);
} catch (Exception ex) {
ex.printStackTrace();
}
You have to code your getConnection() method to return a valid Database Connection.
I would suggest using Statement.executeUpdate method, since it returns an integer. So after performing this delete query you will also have information if you really deleted any records (in this case you would expect this method to return 1, since you are using LIMIT=1). I would also suggest closing Statement as soon as you don't need it, here is skeleton implementation:
private void performDelete(Connection conn, String deleteQuery, int expectedResult) throws SQLException {
Statement stmt = conn.createStatement();
int result = -1;
try {
result = stmt.executeUpdate(deleteQuery);
if(result != expectedResult) {
//Here you can check the result. Perhaps you don't need this part
throw new IllegalStateException("Develete query did not return expected value");
}
} catch(SQLException e) {
//Good practice if you use loggers - log it here and rethrow upper.
//Or perhaps you don't need to bother in upper layer if the operation
//was successful or not - in such case, just log it and thats it.
throw e;
} finally {
//This should be always used in conjunction with ReultSets.
//It is not 100% necessary here, but it will not hurt
stmt.close();
}
}

Categories