while loop with mysql java database [duplicate] - java

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.

Related

searchStudentDetails() method does not show data how can i fetch the particular name details? [duplicate]

This question already has an answer here:
Check if ResultSet is empty in Java [duplicate]
(1 answer)
Closed 1 year ago.
public void searchStudentDetails() throws SQLException {
DatabaseConnection dbms=new DatabaseConnection("jdbc:mysql://localhost:3306/Studentdb","root","root");
Connection con= dbms.getConnection();
Scanner obj=new Scanner(System.in);
System.out.println("Enter your name:");
String inputname=obj.next();
String sql="select *from student where name=? ";
PreparedStatement stmt=con.prepareStatement(sql,ResultSet.TYPE_SCROLL_INSENSITIVE,ResultSet.CONCUR_UPDATABLE);
stmt.setString(1, inputname);
ResultSet rs=stmt.executeQuery();
if(rs.next() ==false)
{
System.out.println("no such data is found");
}
else
{
while(rs.next())
{
rs.previous();
System.out.println(rs.getString(1)+" "+rs.getString(2)+" "+rs.getString(3)+" "+rs.getInt(4));
}
}
stmt.close();
con.close();
}
Output: in console, it shows nothing.
when I enter the wrong name if() condition is working fine but else condition does not fetch any data any modifications?
Rs.next() advances to the next record. You call it twice, once in the if and once in the while.

I want to delete a tables row using Scanner from Java [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
I have connected my DB with eclipse and i want to give the administrator the permission to delete a member putting the members id from Scanner from a table that I have created
public void processDelete() {
try {
String url = "jdbc:mysql://localhost:3306/labdb";
String user = "****";
String password = "***";
Connection myConn = null;
myStmt = null;
ResultSet myRs = null;
Scanner keyboard=new Scanner(System.in);
System.out.println("Enter the id you want to delete");
int id=keyboard.nextInt();
int rowsAffect=myStmt.executeUpdate(
"delete from members " +
"where member_id='"+id+"' ");
} catch (Exception exc) {
exc.printStackTrace();
}
and i get this error
java.lang.NullPointerException
at DeleteMembers.processDelete(DeleteMembers.java:24)
at main.main(main.java:67)
You get the java.lang.NullPointerException because both your Connection and Statement are null.
You first need to initialize Connection by connectiong with your database.
Use :
Class.forName("YourDriver").newInstance();
to register your databese driver,
myConn = DriverManager.getConnection(dbURL);
To inisialize your Connection
Then you should do :
myStmt = myConn.createStatement()
To inisialize Statement
And after all that you can use your statement to exequte a query in the database

how to handle java sql exception:exhausted result set [duplicate]

This question already has answers here:
SQLException: Exhausted Resultset
(3 answers)
Closed 7 years ago.
i have problem with the below code. help me!!
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection conn=DriverManager.getConnection("jdbc:oracle:thin:#127.0.0.1:1521:xe","system","**********");
Statement st=conn.createStatement();
String sql="select password from db where username='user'";
ResultSet rs=st.executeQuery(sql);
rs.next();
String password=rs.getString("password");
if(password.equals(pass))
{
RequestDispatcher rd=req.getRequestDispatcher("/home.jsp");
rd.forward(req,res);
}
else
{
out.println("invalid username and password");
}
when i execute this code i am getting an java sql exception : exhausted result set. thanks in advance...
Instead of using rs.next();, use it with while e.g while(rs.next()). Once you got the resultset, the pointer will point to the first record. Each time you do a rs.next(), the pointer will advances to the next record. If you use with while, once you reach to the end of your resultset, rs.next() will return false once all records are iterated. In your case, since you are not checking whether resultset has exhausted and trying to advanced the pointer, you are getting the exception.
That is correct, because if you enter wrong username or password, NO record will be returned. So, when you use the rs.next(); in this case, it is trying to access the first row of the empty result set
String password=rs.getString("password");//error, if rs is empty
in the where clause you are not using user variable
where clause should be where username='"+user+"'";
and
instead of
rs.next();
use
if(rs.next())
{
String password=rs.getString("password");
........
}

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

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

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.

Categories