I am developing a project for Online Banking System. I want to retrieve a data from database using JDBC. However, it is showing Exhausted result exception though the query is returning a row in SQLPlus. Please Help. Here's the Code:
try
{
Class.forName("oracle.jdbc.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "hr", "XXXXXX");
String pass = 'sid';
String user = 'sid';
String accountnumber = '2345';
String sql = "select * from user_info where account_number=?";
s1 = con.prepareStatement(sql);
s1.setString(1,accountnumber);
rs1 = s1.executeQuery(sql);
rs1.next();
if(user.equals(rs1.getString("user_name")))
{
if(pass.equals(rs1.getString("password")))
{
if(accountnumber.equals(rs1.getString("account_number")))
{
new AccountInformation(accountnumber).setVisible(true);
}
else
{
JOptionPane.showMessageDialog(this, "Account Number is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "Password is Incorrect");
}
}
else
{
JOptionPane.showMessageDialog(this, "User Name is Incorrect");
}
}
catch(Exception e)
{
JOptionPane.showMessageDialog(this,e);
}
You threw away your bind parameter when you passed the SQL to Statement#executeQuery - use this one from PreparedStatement...
rs1=s1.executeQuery();
// rs1=s1.executeQuery(sql);
// check if you got a row
if (rs1.next()) {
// as before....
}
Related
I'm very new to JAVA so this is probably an easy solution.
I'm looking to design a login system using differnt users from a database.
They are seperated by a "Yes" column in the database.
It currently signs in the manager using the IF statement but stops there and won't sign in when using credetials of a staff member.
signIn.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
try{
Class.forName(DRIVER);
// Connection to the Database
con = DriverManager.getConnection(DATABASE_URL,"root","");
// Gets text from textfields and assigns them to variables
s1 = tfUsername.getText();
s2 = tfPassword.getText();
Statement st = con.createStatement();
// SQL Statements
st.executeQuery("SELECT * FROM login WHERE UName= '"+s1+"' and PWord = '"+s2+"'");
// Extracts data from statement to a result set
ResultSet rs = st.getResultSet();
if (rs.next())
{
String Username = rs.getString("UName");
String Password = rs.getString("PWord");
String staff = rs.getString("Staff");
String management = rs.getString("Management");
if(Username.equals(s1) & Password.equals(s2) & management.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1 );
ManagerDashboard.main(args);
signInFrame.setVisible(false);
}
if(Username.equals(s1) & Password.equals (s2) & staff.equals("Yes"))
{
JOptionPane.showMessageDialog(null, "Login Successful, Hello " + s1);
StaffDashboard.main(args);
signInFrame.setVisible(false);
}
}
else
{
JOptionPane.showMessageDialog(null, "Login Failed");
}
}
// SQL Catch block to catch errors
catch(SQLException s){
}
// Catch block to catch ActionListener errors
catch (Exception e1){
}
};
});
code in update button
String password = new String(oldPass.getPassword());
String newPassword = new String(newPass.getPassword());
String realpass = zz.getText();
String us = z.getText();
if(password.equals(realpass))
{
System.out.println("ok");
String query = "UPDATE user SET password = '"+newPassword+"' WHERE username = '"+us+"'";
try{
Statement st = (Statement) con.prepareStatement(query);
int i = st.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null, "Ooopps! I guess you should call your programmer. ^^");
}
}catch(Exception e){
System.out.println(e);
}
}
code in log in
Methods m = new Methods();
String pass = new String (password.getPassword());
String user = username.getText();
if(m.logInUser(user, pass)==true){
form2 f = new form2();
f.setUser(user);
f.setPass(pass);
f.setVisible(true);
this.dispose();
}....and so on....
code for method log in user
public boolean logInUser(String user, String pass){ //true = nakarecord na sa database login form
try{
String query = "Select * from user where username = ? && password = aes_encrypt('"+pass+"', 'nicanor')";
PreparedStatement pst = (PreparedStatement) con.prepareStatement(query);
pst.setString(1,user);
ResultSet rs = pst.executeQuery();
if(rs.next()){
return true;
}
else{
return false;
}
}
catch(Exception e){
System.out.println(e);
return false;
}
}//logInUser
it says successfully connected in sql and the database is updated but i cant see the next form that should pop up after i entered the updated password
There are few problems with your code:
(1) In your update() logic, you are using the mix of PreparedStatement and Statement together, rather use always use PreparedStatement to bind the input parameters, otherwise they (statements/queries) are prone to SQL injection attacks.
You can refer the below code with inline comments to bind the input parameters with PreparedStatement:
//Write the SQL query with ? to bind the parameters in PreparedStatement
String query = "UPDATE user SET password = ? WHERE username = ?";
PreparedStatement pstmt = null;
try{
//create the PreparedStatement object
pstmt = con.prepareStatement(query);
//bind the input parameters using setString()
pstmt.setString(1, newPassword);
pstmt.setString(2, us);
//execute the prepare statement now
int i = pstmt.executeUpdate(query);
if(i!=0){
JOptionPane.showMessageDialog(null, "Your password
is successfully changed!");
}
else{
JOptionPane.showMessageDialog(null,
"Ooopps! I guess you should call your programmer. ^^");
}
} catch(Exception e){
System.out.println(e);
} finally {
if(pstmt != null)
pstmt.close();
if(con != null)
con.close();
}
Also, remember that database resources are costly and you need to close the resources in the finally block as shown above, otherwise you will end up with resource leaks.
(2) In your logInUser() logic, you are using && which is incorrect, rather in sql you need to use AND operator as shown below:
String query = "Select * from user where username = ?
AND password = aes_encrypt('"+pass+"', 'nicanor')";
I've been trying to make a login page and have run into a problem with pulling information from the database containing User credentials. When running the code I get the following error "Error: DB2 SQL Error: SQLCODE=-206, SQLSTATE=42703, SQLERRMC=USERNAME, DRIVER=3.68.61" meaning (I think) that the column username cannot be located, but it is there. The table USERS contains the columns username, password, f_name, and l_name. The username and password for this application are collected via a JSP and passed to a servlet which in turn calls the following .java which has been passed both the username and password entered by the user:
public class Database {
public String lookup( String username, String password) throws SQLException {
Connection connection = null;
PreparedStatement statement = null;
ResultSet resultset = null;
String f_name = "";
String query = "SELECT f_name FROM USERS WHERE username = ? AND password = ?";
try
{
System.out.println("Connecting to Database");
Class.forName("com.ibm.db2.jcc.DB2Driver");
connection = DriverManager.getConnection("jdbc:db2://ipaddress:port/database name", "username", "userpassword");
System.out.println("Connection Successful");
statement = connection.prepareStatement(query);
statement.setString(1, username);
statement.setString(2, password);
resultset = statement.executeQuery();
if( resultset.next())
{
f_name = resultset.getString("f_name");
}
}
catch(ClassNotFoundException error)
{
System.out.println("Error: " + error.getMessage());
}
catch ( SQLException error)
{
System.out.println("Error: " + error.getMessage());
}
finally
{
if( connection != null)
{
connection.close();
}
if( statement != null)
{
statement.close();
}
if( resultset != null)
{
resultset.close();
}
}//end finally
return f_name;
}
}
Any ideas on what is going on?
42703 means An undefined column, attribute, or parameter name was detected.
Here is the link with different DB2 error codes https://urssanj00.wordpress.com/2008/03/04/db2-sql-error-code-and-description/
Could that be that you created your columns in lowercase? Try select colname from syscat.columns where tabname = 'USERS'. If the columns show in lowercase you'd have to quote them in every query: select "f_name" from users where "username" = 'whatever'.
I am trying to verify username and password with MySQL. But it's not working. I can't find the problem. Can anybody help me fix it?
private void jButton2ActionPerformed(java.awt.event.ActionEvent evt) {
String user = jTextField1.getText();
char[] pass = jPasswordField1.getPassword();
try
{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
while (rs.next())
{
if (user.equals(rs.getString("username")))
{
if (pass.equals(rs.getString("password")))
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}
Actually I think it is not checking the enteries with username and password in database. am I right?
Firstly, select by username, then hash the user entered password en check if it matches the hashed password in the database. I suggest something like SHA-2
I also suggest you write classes to handle your code, i.e a User class..
You also forgot to close your ResultSet
One more thing, use PreparedStatement
You are checking for password and username match 2 times.
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
There you already check the password and user, First you shuld check if the password its not stored as MD5 or any other hash type
After that sql you only need to check if its returns any row like #Prabhakaran says
Check code which is written is connecting to database, password is not there in the below code
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Second is check the user and pass variable is getting the value from the action event.
Do like this
Statement stat = con.createStatement();
user = user.toLowerCase();
pass = pass.toLowerCase();
String sql = "Select * from tbl_User Where LOWER(username)='" + user + "' and LOWER(password)='"+pass+"'";
rs = stat.executeQuery(sql);
if(rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
First things first.
Code will only be used to validate the error. So you must paste the error fired by your program.
Since we don't have enough information to the problem, I will try to help you out.
1- It seems your connection variable missing the "Connection" try this :
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/"DATABASENAME"?useTimezone=true&serverTimezone=UTC","USERNAME","PASSWORD");
2 - You already made the if statement to the query in the beginning, so you don't have to start all over again with You can simply type :
if (rs.next()) {
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
} then carry on with the exception part
this is the code :
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/JEREN","root","");
Statement stat = con.createStatement();
String sql = "Select * from tbl_User Where username='" + user + "' and password='"+pass+"'";
rs = stat.executeQuery(sql);
if (rs.next())
{
JOptionPane.showMessageDialog(null,"Login Successfully");
main.getWindows();
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Password");
}
else
{
JOptionPane.showMessageDialog(null,"Incorrect Login");
}
stat.close();
con.close();
}
catch (SQLException | HeadlessException e)
{
//e.printStackTrace();
JOptionPane.showMessageDialog(null,"PROBLEM OCCURED !!!! ");
}
catch (ClassNotFoundException ex) {
Logger.getLogger(Users.class.getName()).log(Level.SEVERE, null, ex);
}
// TODO add your handling code here:
}`
I've got the following code to query a database! But the code inside the while loop doesn't get executed! No messagebox, just doesn't get executed! Can anyone help me! Result set is not empty! When I print the same value out of the try catch block it gets executed and the right values get printed! Th DB connection is a standard MySQL DB connection class!
database = new DBConnection();
String dept = txtSearch.getText();
String Query = "SELECT * FROM department where dept_name= '" + dept + "'";
ResultSet set = database.queryDatabase(Query);
try {
if (set.next() == false) {
JOptionPane.showMessageDialog(null, "No Matchs found for the search query! Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, ex.getMessage(), ex.getCause().toString(), JOptionPane.ERROR_MESSAGE);
}
You're throwing out the first row of your query by calling set.next() and then ignoring the data in the row here:
if (set.next() == false) { // ***** here on this line
JOptionPane.showMessageDialog(null, "No Matchs found for the search query!
Try Again.", "Search Error", JOptionPane.ERROR_MESSAGE);
} else {
while (set.next()) {
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
}
Instead be sure to extract information from your ResultSet every time you call next() and it returns true.
You could do something like this instead:
int setCount = 0;
while (set.next()) {
setCount++;
System.out.print(set.getString("dept_name"));
txtName.setText(set.getString("dept_name"));
txtDes.setText(set.getString("dept_desc"));
}
if (setCount == 0) {
// show a warning to the user that the result set was empty
}