else statement not executing with Object method Call - java

For some reason, I have an else if statement that does not want to run. The conditions (I think) have been met.
int codeCheck = Integer.parseInt(itemCode);
DataAccessImpl da = new DataAccessImpl();
if(!rs.wasNull()) {
while(rs.next()) {
Products temp = new Products(rs.getString(1), rs.getString(2), rs.getDouble(3), rs.getBoolean(4));
productsList.add(temp);
request.setAttribute("productsList", productsList);
request.getRequestDispatcher("Scan.jsp").forward(request, response);
}
}
else if(da.codeExists(codeCheck) == false){
Products wrongCode = null;
productsList.add(wrongCode);
System.out.println("THIS IS EXECUTING!");
request.setAttribute("productsList", productsList);
request.getRequestDispatcher("Scan.jsp").forward(request, response);
}
Here's the method in the DataAccessImpl Class
public boolean codeExists(int code) {
final String SELECT_QUERY = "SELECT * FROM productcatalogue WHERE code = ?";
try {
PreparedStatement statement = conn.prepareStatement(SELECT_QUERY); // Create query statement
statement.setInt(1, code);
ResultSet queryResult = statement.executeQuery();
if (!queryResult.next()) { // Check if code entered exists
return false;
}
} catch (SQLException sqlException) {
sqlException.printStackTrace();
}
return true; //Otherwise the item exists
}

if you are sure rs was surely null and the first if is not met then definitely it will go to your else if and will check if (da.codeExists(codeCheck) == false) and if this is also true then it will surely execute so you make sure that first if is false and else if is true other wise according to the design pattern it will not be executed.

Related

Looping try/catch statement

I'm trying to take two random rowid from my database. Everything works but I have a scenario when there is only one rowid. I want to make a loop on my try/catch until there is second number in my database.
What I'm doing wrong? Thank you
public void Kaslaimejo() {
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer value1 = null, value2 = null;
Integer judesiukas1 = null, judesiukas2 = null;
int a = 0;
int k = 15; // kiek kartu? Reikia infinity padaryti
for (a = 0; a < 3; a++) {
try {
Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if (rs.next()) {
value1 = rs.getInt("rowid");
if (rs.next()) {
value2 = rs.getInt("rowid");
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, value1);
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, value2);
int buvolala2 = buvo2.executeUpdate ();//
i++;
}
System.out.println("Pirmas zaidejas" + value1); // atspausdina 1 random zaideja is duomenu bazes
System.out.println("Antras zaidejas" + value2); // atspausdina 2 random zaideja is duomenu bazes
}
} catch (SQLException e) {
a--;
//System.out.println(e.getMessage());
}
}
}
Right now my program loops two times and then gives me SQLException. How I can loop my program until there is no SQLException?
OK, I've tried to write what I think you're trying to do.
You wait for ever until someone puts at least two entries in the database.
You extract two values, process them, then wait some more.
Some points to watch out:
1. Object comparisons need to be made with .equals() not with ==
2. You might want to provide some way to break out of the infinite loop I've written (while(true)).
3. Careful with null values. They might produce NullPointerException.
4. Try to break up your code into methods. Each large block of code could go into each own method.
public void Kaslaimejo(){
String sql = "SELECT rowid FROM Zaidejai WHERE Pirmas < 4 ORDER BY random() LIMIT 2";
Integer judesiukas1 = null, judesiukas2 = null;
while(true) {
List<Integer> values = new ArrayList<>();
while (values.size() < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql)) {
if( rs.next() ){
Integer value = rs.getInt("rowid");
values.add(value);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
try( Connection conn = Serveris.connect()) {
PreparedStatement buvo = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo.setInt(1, i);
buvo.setInt(2, values.get(0));
int buvolala = buvo.executeUpdate ();
PreparedStatement buvo2 = conn.prepareStatement("UPDATE Zaidejai SET Numeriukas = ? WHERE rowid = ?");
buvo2.setInt(1, i);
buvo2.setInt(2, values.get(1));
int buvolala2 = buvo2.executeUpdate ();//
i++;
}catch (SQLException e) {
e.printStackTrace();
}
Connection conn = Serveris.connect();
try {
PreparedStatement pstmt = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
PreparedStatement pstmt2 = conn.prepareStatement("SELECT Pirmas FROM Zaidejai WHERE rowid = ?");
pstmt.setInt(1, values.get(0));
pstmt2.setInt(1, values.get(1));
ResultSet myrsv = pstmt.executeQuery();
ResultSet myrsv2 = pstmt2.executeQuery();
{
if (myrsv.next()) {
judesiukas1 = myrsv.getInt("Pirmas");
if (myrsv2.next()) {
judesiukas2 = myrsv2.getInt("Pirmas");
}
}
//System.out.println("Pirmo zaidejo veiksmas" + myrsv.getInt("Pirmas"));
//System.out.println("Antro zaidejo veiksmas" + myrsv2.getInt("Pirmas"));
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (judesiukas1.equals(judesiukas2)) // careful here. NullPointerException may happen.
{
try {
PreparedStatement laim = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?"); // ble ble update reikia naudoti , o ne insert into. Insert kai sukuriame nauja kazka tik
PreparedStatement laim2 = conn.prepareStatement("UPDATE Zaidejai SET Rezultatas = ? WHERE rowid = ?");
laim.setString(1, "Lygiosios");
laim.setInt(2, values.get(0));
laim2.setString(1, "Lygiosios");
laim2.setInt(2, values.get(1));
int irasyk = laim.executeUpdate (); // kodel executeupdate, o ne executequery????
int irasyk2 = laim2.executeUpdate (); // kodel executeupdate, o ne executequery????
{
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.print("Lygiosios");
} else {
// (1) - Rock
// (2) Scissors
// (3) - Paper
switch (values.get(0)){
case 1:
if (judesiukas2 == 2)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 2:
if (judesiukas2 == 3)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
case 3:
if (judesiukas2 == 1)
System.out.print("Zaidejas 1 wins!");
else
System.out.print("Zaidejas 2 wins!");
break;
}
}
try {
conn.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
The logic becomes easier if you add the values to a list
var values = new ArrayList<Integer>();
while (values.Count < 2) {
try (Connection conn = Serveris.connect();
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery(sql))
{
while (values.Count < 2 && rs.next()) {
Integer v = rs.getInt("rowid");
values.Add(v);
}
} catch (SQLException e) {
}
}
//TODO: process the values here
The advantage is, that you can retrieve one value at the first database query and the second at a later one or both in the same round and you don't have to keep track of which one of two variables to use.
(Bear with me with the syntax details, I'm not a Java programmer.)
How i can loop my program until there is no SQLException?
Change this (because, it will only allow to loop two times)
for (a = 0; a < 2; a++) {
to
while(true)
Put everything inside while(true), if exception occurred, then it will come out from the while loop. Something similar :
try
{
while(true)
{
...
...
}
...
}
catch(SQLException e)
{
// do somthing
}

if-else loop condition is not working using java swing?

I'm trying to fetch database records of user name and password and validate using if-else statement. Final else statement is not displaying message dialog. I'm stuck with this, suggest me a solution and say where i done mistake.
My complete code
String s1 = id.getText();
String s2 = new String(pass.getPassword());
try
{
Class.forName("org.apache.hive.jdbc.HiveDriver");
Connection con = DriverManager.getConnection("jdbc:hive2://localhost:10000/twitter_db","arunachalam","");
String sql = "select userid, password from user_reg where userid='"+s1+"'";
PreparedStatement ps = con.prepareStatement(sql);
ResultSet rs = ps.executeQuery();
while(rs.next())
{
if((rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
dispose();
showMessageDialog(null,"Login Successfully");
new UserPage().setVisible(true);
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else
{
showMessageDialog(null,"Invalid User");
}
}
}
catch(Exception e)
{
showMessageDialog(null, e);
}
You checked same condition twice for user id and password so every time it checks first else if statement and it does't satisfy final else if.
Obeserve in your below piece of source code.
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}
May be you are trying for below code that i have updated
// check for user id not equal
else if((!rs.getString("userid").equals(s1)) && (rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect User Id");
}
else if((rs.getString("userid").equals(s1)) && (!rs.getString("password").equals(s2)))
{
showMessageDialog(null,"Incorrect Password");
}

APOSTROPHE issue with java and SQL

I have code, where I have single quote or APOSTROPHE in my search
I have database which is having test table and in name column of value is "my'test"
When running
SELECT * from test WHERE name = 'my''test';
this works fine
If I use the same in a Java program I am not getting any error or any result
But If I give the name with only single quote then it works
SELECT * from test WHERE name = 'my'test';
Could you please help me out to understand.
Java code is
Connection con = null;
PreparedStatement prSt = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.
getConnection("jdbc:oracle:thin:#localhost:1521:orcl"
,"user","pwd");
String query = "SELECT * from "
+ "WHERE name = ? ";
prSt = con.prepareStatement(query);
String value = "my'mobile";
char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++) {
if (content[i] == '\'')
{
result.append("\'");
result.append("\'");
}
else
{
result.append(content[i]);
}
}
prSt.setObject(1, result.toString());
int count = prSt.executeUpdate();
System.out.println("===============> "+count);
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
} finally{
try{
if(prSt != null) prSt.close();
if(con != null) con.close();
} catch(Exception ex){}
}
You don't have to escape anything for the parameter of a PreparedStatement
Just use:
prSt = con.prepareStatement(query);
prSt.setString("my'mobile");
Additionally: if you are using a SELECT statement to retrieve data, you need to use executeQuery() not executeUpdate()
ResultSet rs = prst.executeQuery();
while (rs.next())
{
// process the result here
}
You might want to go through the JDBC tutorial before you continue with your project: http://docs.oracle.com/javase/tutorial/jdbc/index.html

Error: MySQLSyntaxErrorException in a java-based web app [duplicate]

This question already has answers here:
Passing table name as parameter of prepared statement [duplicate]
(3 answers)
Closed 6 years ago.
public List<User> arrangeUsers(String option) {
String query = "";
if (option.equals("lastNameAsc")) {
query = "SELECT * FROM ? ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query = "SELECT * FROM ? ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query = "SELECT * FROM ? ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
if (searchList.size() > 0) {
stmt.setString(1, "search_results");
searchList.clear();
listChoice = true;
} else {
stmt.setString(1, "users");
users.clear();
listChoice = false;
}
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
The above method returns an error:
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 ''users' ORDER BY lastName DESC' at line 1 " error.
The method is supposed to arrange a list of users (a table) according to the order required by the client. Any suggestions what is the reason for the error message? I am ready to provide any additional details if necessary.
A table name can't be used as a parameter. It must be hardcoded. You can do something like:
public List<User> arrangeUsers(String option) {
String query = "SELECT * FROM ";
if (searchList.size() > 0) {
query += "search_results ";
searchList.clear();
listChoice = true;
} else {
query += "users ";
users.clear();
listChoice = false;
}
if (option.equals("lastNameAsc")) {
query += "ORDER BY lastName ASC;";
} else if (option.equals("lastNameDesc")) {
query += "ORDER BY lastName DESC;";
} else if (option.equals("dobAsc")) {
query += "ORDER BY dateOfBirth ASC;";
} else if (option.equals("dobDesc")) {
query += "ORDER BY dateOfBirth DESC;";
}
boolean listChoice;
try (Connection conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
PreparedStatement stmt = conn.prepareStatement(query);) {
ResultSet result = stmt.executeQuery();
while (result.next()) {
User user = new User();
user.setFirstName(result.getString("firstName"));
user.setLastName(result.getString("lastName"));
user.setDob(result.getDate("dateOfBirth"));
user.setPhoneNumber(result.getString("phoneNumber"));
user.setEmail(result.getString("email"));
user.setUserID(result.getInt("id"));
if (listChoice) {
searchList.add(user);
} else {
users.add(user);
}
}
} catch (SQLException sqle) {
System.err.println(sqle);
sqle.printStackTrace();
return null;
}
if (listChoice) {
return searchList;
} else {
return users;
}
}
Hope it helps.

to check whether the search element isn't available in DB

I'm using phpmy admin and I need to Display "Not Found" message in case searching element is not found in the DB.
Used code is here.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
I used this method to search empId ,if empId is not available in db I need to display a message.Please give me a solution how to detect, if empId is not available in DB.
if (rs != null)
{
out.println("result set has got something");
while (rs.next())
{
//I am processing result set now
}
}
else
{
out.println("Not Found");
}
Use if statement like this
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
{
do
{
// If there is data, then process it
}
while(rs.next());
}
else
System.out.println("Not Found");
Added parse of text to integer, assuming empId is an integer.
int empId = Integer.parseInt(txtempId.getText());
try (Connection c = DBconnect.connect()) {
String sql = "SELECT *" +
" FROM nonacademic" +
" WHERE empId = ?";
try (Statement s = c.prepareStatement(sql)) {
s.setInt(1, empId);
try (ResultSet rs = s.executeQuery()) {
if (! rs.next()) {
// not found
} else {
// found, call rs.getXxx(...) to get values
}
}
}
}
Just use the basic simple if & else statement. If the ResultSet is "null" or it doesn't contain any record display the Message otherwise read data & display.
Connection c = DBconnect.connect();
Statement s = c.createStatement();
String e = txtempId.getText();
ResultSet rs = s.executeQuery("SELECT * FROM nonacademic WHERE empId='" +e+ "'");
if(rs.next())
// record found do the processing
else
System.out.println("Not Found");
String e = txtempId.getText();
String sql="select *from nonacademic where empId='"+ e+"' ";
try {
boolean status=DatabaseConnection.checkValue(sql);
if (status) {
JOptionPane.showMessageDialog(null,
"This id is available");
} else {
JOptionPane.showMessageDialog(null,
"Not found");
}
} catch (Exception e) {
}
This method return check whether the search element is exist or not
public static boolean checkValue(String sql) throws Exception {
boolean b = false;
ResultSet rst = null;
Statement st = getStatement();
rst = st.executeQuery(sql);
if (rst.next()) {
b = true;
}
return b;
}

Categories