Java - Issue with boolean value not being changed [duplicate] - java

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm working on a student database managing program, and am working on the login phase. I query the database for the students id and password and try and match an entry to what the student enters. When a match is found login should be set to true, and it should go to the next page, but for some reason its never passing my if then statement. I'm not entire sure whats wrong,the code for this is below. You'll notice the system.out.println statements, those are there so I can see if it is actually going through the database correctly, and as far as I can tell it does, but login next gets set to true. I would really appreciate any help.
public void actionPerformed(ActionEvent e)
{
//int i;
//String name;
if(e.getSource()==logInButton)
{
String name="";
String password="";
name=inputField.getText();
password=inputField2.getText();
System.out.println(name);
System.out.println(password);
boolean login = false;
try {
connection = DriverManager.getConnection(connectionString, username, pass);
PreparedStatement statement = (PreparedStatement) connection.prepareStatement("SELECT * FROM students");
data = statement.executeQuery();
while(data.next()){
System.out.println(data.getObject("student_id"));
System.out.println(data.getObject("password"));
if (data.getObject("student_id") == name && data.getObject("password") == password){
login = true;
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
if(login == true){
System.out.println("login = true");
logInPanel.setVisible(false);
postLogInPanel.setVisible(true);
}
}

In Java, == is object identity. a==b is true if a and b are references to the same object in memory. When you're comparing reference types, like Strings and possibly whatever e.getSource() returns, you should use the equals method to see if the values are the same.

Related

check row if not exist mysql and got output to boolean bukkit

I have tried this so many times but I never did it, this is my code
public static Boolean checkhaveguild(String name) {
try {
Statement statement = connection.createStatement();
PreparedStatement ps = connection.prepareStatement("SELECT * FROM guild");
System.out.println(statement.execute("SELECT * FROM guild WHERE name = "+name+""));
System.out.println("----------");
} catch (SQLException e) {
throw new RuntimeException(e);
}
return false;
}
I am doing a guild plugin on BungeeCord and getting data from MySQL
The code is about checking if the row does not exist and output to boolean
I'd suggest you to learn more about the basics of programming in Java! Minecraft is a great way to start into programming, but you should be interested in doing things properly.
public static boolean hasGuild(String name) {
PreparedStatement statement = null;
ResultSet resultSet = null;
try {
statement = connection.prepareStatement("SELECT COUNT(name) FROM guild WHERE name = ?");
statement.setString(1, name);
resultSet = statement.executeQuery();
if (resultSet.next()) return resultSet.getInt(1) > 0;
} catch (SQLException e) {
// TODO properly handle exception
} finally {
if (resultSet != null) {
try {
resultSet.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
if (statement != null) {
try {
statement.close();
} catch (SQLException e) {
// TODO properly handle exception
}
}
}
return false;
}
Some thoughts on what this code is doing:
Asking the database for the number of rows whose name column matches the given string. Always make sure that you only request the data that's necessary for your purpose. Requesting all columns with their data is overkill if you only want to answer if there are any rows or not.
If the number of rows is greater than zero, it'll return true, because there are rows with a matching name column.
Some thoughts you should make yourself:
What is contained in the name column? If it's the guild's name, then that's fine, but if that's the player's name you should consider re-thinking your code. Player's in Minecraft can change their name and hence would lose their guild on your server. Players in Minecraft are uniquely identified by their UUID, which will never change. Maybe consider using the UUID then!
In order for the query to be as fast a possible you should set an INDEX on the name column. That will speed up the lookup proccess even if there are plenty of rows!
Nevertheless: Welcome to StackOverflow! I hope that I could help you and I wish lot's of fun with programming.
in the try, i try sout resultSet and statement before close and it send this to me
resultSet :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = 'a'
statement :
com.mysql.cj.jdbc.ClientPreparedStatement: SELECT COUNT(name) FROM guild WHERE name = ** NOT SPECIFIED **
and return false is my test at last it will return true if it have if not it will return false

Comparing MySQL DB object with a String in Java

I'm working on a program to manage students in a DB, and I'm working on the part where students can sign in, but for some reason I can never get the if statement to be true. I'm thinking it has something to do with the value I'm getting from the database being an object as opposed to a String. I've tried casting it to String but I get an error, is there anyway I can compare these two values? My code is below so you can take a look. I know there are other questions like this, but I've not been able to get any of their solutions to work. Thanks so much in advance.
public void actionPerformed(ActionEvent e)
{
//int i;
//String name;
if(e.getSource()==logInButton)
{
String name="";
String password="";
name=inputField.getText();
password=inputField2.getText();
try {
connection = DriverManager.getConnection(connectionString, username, pass);
PreparedStatement statement = (PreparedStatement) connection.prepareStatement("SELECT * FROM students");
data = statement.executeQuery();
while(data.next()){
//login = data.getObject("student_id").equals(name) && data.getObject("password").equals(password);
if(data.getObject("student_id").equals(name) && data.getObject("password").equals(password))
{
System.out.println("login = true");
logInPanel.setVisible(false);
postLogInPanel.setVisible(true);
}
}
} catch (SQLException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
Instead of doing:
data.getObject("student_id");
Try:
data.getString("student_id");
This is assuming your student_id field is some sort of char field. Also you may want to try comparing using
.equalsIgnoreCase //instead of .equals for username unless it is case sensitive...
first of all you need to query the database like
SELECT * FROM students where username='THE ENTER USERNAME' and password='Entered password'
if the size of the result set == 1 then login else invalid credentials or user doesn't exit...
Data of the object can be got via
data.getInt("student_id"); ..

while loop with mysql java database [duplicate]

This question already has answers here:
How do I compare strings in Java?
(23 answers)
Closed 8 years ago.
I'm new student with Java and I'm trying to make an app to see if the username and password do exist so I wrote this code and there in the main class I call this method and see if a = true or false.
i tried putting System.out.print statement in the while loop and it didn't show up which means the while loop doesn't works.
public void checkUserName(String username,String password) throws SQLException, ClassNotFoundException
{
openconnection();
String query ="SELECT * FROM hema.employee";
Statement stm=(Statement) con.createStatement();
ResultSet rs;
rs = stm.executeQuery(query);
while(rs.next()){
String un,pass;
un=rs.getString("UserName");
pass=rs.getString("PassWord");
System.out.println("hi your answer is "+ a);
if(un==username&&pass==password){
System.out.println("if Works");
a=true;
break;
}
}
}
You don't want to compare your strings with == but with .equals.
if(un.equals(username) && pass.equals(password))
Apar from that, this is very slow for a big userbase. Instead you could query for username and password in the database and just check if you get back a result or not.

Java IF ELSE statements

Quick question. I got a code below, which checks with a database whether a given ID is available in the database, if so, it retrieves all attendance histories for the ID, otherwise if the ID didn't exist in the database it should display an error message. The code I got however, always says that the record has been attached, and then displays the error message as well regardless whether the ID exists or not. I think I probably have to change the order of the code or such? Could you please advise?
JButton button = new JButton("Submit");
button.addActionListener(new ActionListener() {
#SuppressWarnings("unused")
public void actionPerformed(ActionEvent arg0) {
String studentID = textField.getText();
try {
Statement st = con.con.createStatement();
ResultSet rs = st.executeQuery("SELECT StudentID, date FROM attendance WHERE StudentID ="+textField.getText());
while ( rs.next() ) {
String student = rs.getString("StudentID");
String date = rs.getString("date");
System.out.println(student+"");
System.out.println(date);
}
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance has been registered.");
frmAttendanceHistory.setVisible(false);
if (!rs.next()) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "A record for the given Student ID doesn't exist");
}
}
catch (SQLException e) {
JOptionPane.showMessageDialog(frmAttendanceHistory, "Attendance couldn't be registered. Please try again!");
e.printStackTrace();
}
}
});
You're repeatedly calling rs.next() until it returns false (as otherwise you'll never get out of the while loop) - then you're calling rs.next() again. Why would you expect it to return true then?
I suspect you want something like:
if (rs.next()) {
String student = rs.getString("StudentID");
String date = rs.getString("date");
System.out.println(student+"");
System.out.println(date);
JOptionPane.showMessageDialog(frmAttendanceHistory,
"Attendance has been registered.");
frmAttendanceHistory.setVisible(false);
} else {
JOptionPane.showMessageDialog(frmAttendanceHistory,
"A record for the given Student ID doesn't exist");
}
You're doing a second rs.next, which would go to a second record if there was one. If there's only one (which is already consumed further up in your app), then it fails giving you a success followed by a failure.
while ( rs.next() ) {
followed by
if (!rs.next()) {
Doesn't make any sense as the if will always execute. Your loop will continue until rs.next() returns false.

how to compare the values present in excel table and value taken by the user in java programming

I have used if loop to compare the values present in table and the value entered from the user, but in the code its not entering to if loop rather it is entering to else loop, i need the suggestion for the problem.
Here is the code :
public void idExists(String SkillID) {
try{
Connection conn = dbconnect();
conn.setReadOnly(false);
Statement st = conn.createStatement();
String skilid= "Select [Skill ID]from [Skill Master$]";
ResultSet rs = st.executeQuery(skilid);
while(rs.next()){
String Skill = rs.getString("Skill ID");
System.out.println(SkillID);
}
if (SkillID==Skill) {
System.out.println("the skill id exist");
}
else {
System.out.println("the skill id doesnt exist");
}
endConnect();
}
catch(SQLException e) {
System.err.println("Got an exception in idexist");
System.err.println(e.getMessage());
}
}
}
You're comparing string value by reference.
Since your variable refer to two different String instances with the same value, the condition is false.
You should compare strings using the equals method.
Also, you probably want to put the if inside the loop.
Finally, you should replace all of that code with a (parameterized!) WHERE clause.

Categories