Swager Swager - 1 month ago 9
Java Question

Issues with retrieving data from Access database using criteria from JTextField objects

I have created user login window in java and i am getting some issues regarding retrieving saved data from ms access database.
Here is my code:

package databaseretrievedata;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.*;
import javax.swing.*;
public class Databaseretrievedata {
Databaseretrievedata(){
JFrame edit=new JFrame();
edit.setBounds(300,200,550,120);
edit.setUndecorated(false);
edit.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel p=new JPanel();
p.setBounds(0,0,600,400);
edit.add(p);
JTextField field=new JTextField(20);
field.setBounds(100,200,120,20);
p.add(field);
JTextField field1=new JTextField(20);
field1.setBounds(100,300,120,20);
p.add(field1);
JButton b=new JButton("Click Me");
b.setBounds(0,100,100,20);
p.add(b);
JRootPane pane=b.getRootPane();
pane.setDefaultButton(b);
b.addActionListener(new ActionListener(){
public void actionPerformed(ActionEvent e)
{
try {
Connection conn=DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\MUHAMMAD SHAHAB\\real estate.accdb");
Statement st=conn.createStatement();
String sql="select Username,Password from simba where Username='"+field+"'and Password='"+field1+"'";
ResultSet rs=st.executeQuery(sql);
if(rs.next())
{
JFrame editframe=new JFrame();
editframe.setBounds(300,200,400,200);
editframe.setUndecorated(false);
editframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
editframe.setVisible(true);
}
else
{
JOptionPane.showMessageDialog(null,"No record Found");
}
}
catch (Exception ex)
{
JOptionPane.showMessageDialog(null, ex);
}
}
});
edit.setVisible(true);
}
public static void main(String[] args) {
Databaseretrievedata v=new Databaseretrievedata();
}

}


Here is the file in the database where i saved my data.[![enter image description here][1]][1]

I have created one text field for username and password field for getting password from the user inside JFrame and when i entered the same username and password which i saved in ms access database i got 'No record Found'although i have saved that data in the database and i want this,that when user enter username and password in the provided fields then a new JFrame opens up.
I am not pretty sure where i am doing mistake.

Answer

@Swager you are missing getText() method from your query you should write your sql like this String sql = "select Username,Password from simba where Username='"+field.getText()+"'and Password='"+field1.getText()+"'";

Comments