Making authorization JFrame with MS Access base - java

I'm trying to make a authorization JFrame to MS Access DB, but query does'nt seems to wirk properly. The idea is to intup login and password, and if one of them isn't correct, get a message. My code always sends me to the exception. Here is my code, maybe someone can help me.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class First {
JFrame frame;
JPanel txt, but;
JButton log, ext;
JTextField login;
JLabel l, p;
JPasswordField pass;
PreparedStatement prepst;
ResultSet res;
public First() {
frame = new JFrame("Authorization");
txt = new JPanel();
but = new JPanel();
log = new JButton("Login");
ext = new JButton("Quit");
login = new JTextField(10);
l = new JLabel("Login:");
p = new JLabel("Password:");
pass = new JPasswordField(10);
frame.setSize(400,100);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
txt.add(l);
txt.add(login);
txt.add(p);
txt.add(pass);
frame.add(txt,BorderLayout.NORTH);
but.add(log);
but.add(ext);
frame.add(but,BorderLayout.SOUTH);
log.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
String PathToDataBase = "D:/workspace2/MicrosoftAccessConnection/db";
String DataBase = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb)};DBQ=";
DataBase += PathToDataBase.trim() + ";DriverID=22;READONLY=true}";
Connection con = DriverManager.getConnection(DataBase,"","");
prepst = con.prepareStatement("SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?");
String lll = login.getText();
String ppp = pass.getText();
prepst.setString(1,lll);
prepst.setString(2, ppp);
res = prepst.executeQuery();
if((test(con,lll,ppp)) == true) {
while(res.next()) {
if((lll.equals(res.getString("LOGIN"))) && (ppp.equals(res.getString("PASSWORD")))) {
lol();
} else {
JOptionPane.showMessageDialog(null, "Wrong data");
}
}
}
res.close();
prepst.close();
con.close();
} catch(Exception e) {
JOptionPane.showMessageDialog(null, "Error with connection");
}
}
});
ext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evnt) {
frame.dispose();
}
});
frame.setVisible(true);
}
public void lol() {
JFrame f = new JFrame("SUCCESS");
f.setSize(200,200);
frame.dispose();
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
f.setVisible(true);
}
boolean test(Connection con, String login, String pass) throws SQLException {
int rez = 0;
PreparedStatement st = con.prepareStatement("SELECT COUNT(*) FROM USERS WHERE LOGIN=? AND PASSWORD=?");
st.setString(1, login);
st.setString(2, pass);
ResultSet res = st.executeQuery();
while (res.next()) {
rez = res.getInt(1);
}
st.close();
return rez == 1;
}
public static void main(String[] args) {
new First();
}
}

You're missing a PreparedStatement placeholder character from your SQL, replace
SELECT * FROM USERS WHERE LOGIN= AND PASSWORD=?
with
SELECT * FROM USERS WHERE LOGIN=? AND PASSWORD=?
^
If you're getting an Exception, its always best to display the exception content. You could add this to the exception block:
e.printStackTrace();

Related

multi frame working (admin,user)

i am making java app for my minor project.i am entering correct data but it not allowing to login.i am confused why the code in not working.
there are 2 fields in my database(username and pass ).i am entering correct data but it allowing me to login
`
public class login extends JFrame implements ActionListener{
JButton jb1;
JTextField tf3,tf1,tf2;
ResultSet rs;
String s2,s1,s3;
String a;
Connection con;
login(){
Container c =getContentPane();
c.setLayout(null);
c.setBackground(Color.orange);
jb1=new JButton("submit");
jb1.addActionListener(this);
jb1.setBounds(180,370,100,50);
JLabel jl1=new JLabel("username");
jl1.setBounds(10,60,100,50);
JLabel jl2=new JLabel("password");
jl2.setBounds(10,110,100,50);
JLabel jl3=new JLabel("user or emp");
jl3.setBounds(10,160,100,50);
tf1= new JTextField();
tf1.setBounds(110,70,200,40);
tf2= new JTextField();
tf2.setBounds(110,120,200,40);
tf3=new JTextField();tf3.setBounds(110,180,200,40);
tf1.setText("username");
tf2.setText("password");
c.add(tf1);c.add(tf2);c.add(tf3);
c.add(jl1);c.add(jl2);c.add(jl3);
c.add(jb1);
}
public void actionPerformed(ActionEvent e){
if(e.getSource()==jb1){
s1 = tf1.getText();
s2 = tf2.getText();
s3 = tf3.getText();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:orcl", "scott", "hr");
PreparedStatement ps = con.prepareStatement("select * from login ");
rs = ps.executeQuery();
while(rs.next()) {
String username = rs.getString("username");
String pass = rs.getString("pass");
if ((s1.equals(username)) && (s2.equals(pass))) {
if (s3.equals("Admin")) {
dispose();
home f=new home();
f.setSize(500,500);
f.setTitle("Bank Management System");
f.setVisible(true);
} else if (s3.equals("user")) {
dispose();
} else {
dispose();
}
} else {
JOptionPane.showMessageDialog(null, "User name and password do" + " not match!","ALERT!",JOptionPane.ERROR_MESSAGE);
break;
}
}
}
catch(Exception ex)
{
System.out.println( ex);
}
}
}
public static void main(String[] args) {
login af =new login();
af.setSize(500,500);
af.setTitle("login");
af.setVisible(true);
}
}
`

ResultSet disappears after updating rows

The only thing remotely similar to my issue that I could find was this, however his problem seemed to be from a user error.
Reset cursor position after ResultSet updateRow
My problem is the following: After updating a row I am not able to access any other rows in my ResultSet. The update itself works fine, but if I want to continue I have to restart the application.
Here's the code:
package database;
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Gui extends MyDB {
JFrame f;
JLabel FName;
JLabel LName;
JLabel Age;
JTextField t;
JTextField t2;
JTextField t3;
JButton next = new JButton("next");
JButton update = new JButton("Update");
public Gui() {
frame();
start();
btnAction();
}
public void frame() {
f = new JFrame();
f.setVisible(true);
f.setSize(680, 480);
f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
FName = new JLabel("Name");
LName = new JLabel("Anrede");
Age = new JLabel("age");
t = new JTextField(10);
t2 = new JTextField(10);
t3 = new JTextField(10);
JPanel p = new JPanel();
p.add(FName);
p.add(t);
p.add(LName);
p.add(t2);
p.add(Age);
p.add(t3);
p.add(b1);
p.add(update);
public void btnAction() {
next.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
});
update.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String FName = t.getText();
String LName = t2.getText();
String Age = t3.getText();
try {
System.out.println(rs.getRow());
rs.updateString("FName", FName);
rs.updateString("LName", LName);
rs.updateString("Age", Age);
rs.updateRow();
//System.out.println(rs.getString("FName"));
System.out.println(rs.getRow());
JOptionPane.showMessageDialog(null, "Record updated ");
} catch (Exception ex) {
System.out.println("no");
}
}
});
}
public void start() {
try {
if (rs.next()) {
t.setText(rs.getString("FName"));
t2.setText(rs.getString("LName"));
t3.setText(rs.getString("Age"));
} else {
rs.previous();
JOptionPane.showMessageDialog(null, "no next records");
}
} catch (Exception ex) {}
}
}
Also:
package database;
import java.sql.*;
public class MyDB {
Connection con;
Statement st;
ResultSet rs;
public MyDB() {
connect();
}
public void connect() {
try {
String db = "jdbc:ucanaccess://Datenbank1.accdb";
con = DriverManager.getConnection(db);
st = con.createStatement(ResultSet.TYPE_SCROLL_INSENSITIVE, ResultSet.CONCUR_UPDATABLE);
String sql = "select * from Tabelle1";
rs = st.executeQuery(sql);
} catch (SQLException ex) {
ex.printStackTrace(System.out);
}
}
public static void main(String[] args) {
new Gui();
}
}
Output of System.out.println(rs.getRow()); is '0'.
If I want to click on the 'next' button after updating, the message "no next records" is displayed.
I have tried using rs.first(), rs.beforeFirst() and rs.isBeforeFirst(), none of which have worked.
If it helps, I am following this tutorial, which does not run into the same problem:
https://www.youtube.com/watch?v=NPV2o6YjP10

Setting up JDBC to check for correct username and password

Trying to set up a JDBC that checks a database for a matching username and password, and they when the login button is pressed if matching the user is granted access, I've got my current code here, but I'm unsure what is missing when I launch the program it seems like its not checking the database for the correct information.
Updated:
import java.awt.*;
import java.awt.event.*;
import javax.swing.*;
import java.sql.*;
public class NewClass extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
NewClass() {
//create menu bar
JMenuBar jmb = new JMenuBar();
//set menu bar to the applet
setJMenuBar(jmb);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
jmb.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
jmb.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiLogin = new JMenuItem("Login", 'L'));
optionsMenu.addSeparator();
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(2, 2));
p1.add(new JLabel("Username"));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password"));
p1.add(jtfPassword = new JPasswordField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(backButton = new JButton("Back"));
p2.add(loginButton = new JButton("Login"));
//Panel with image??????
//add panels to frame
JPanel panel = new JPanel(new GridLayout(2, 1));
panel.add(p1, BorderLayout.CENTER);
panel.add(p2, BorderLayout.SOUTH);
add(panel, BorderLayout.CENTER);
setTitle("Main Page");
//listners for exit menuitem and button
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
backButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setSize(500, 500);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the login panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//action listeners for Login in button and menu item
loginButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText()); {
System.out.println("User is validated");
}
} catch (SQLException se) {
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
jmiLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
NewClass.this.dispose();
NewClass.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
log frame = new log();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/test";
static final String USERNAME = "root";
static final String PASSWORD = "root";
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
Make your checkLogin method return boolean type and return true inside if (orPass.equals(password)) { block. Check whether the method true if so grant access.
You are missing a return type in your checkLogin method. You may return a boolean value to validate the user. Also add some logging/sysout to make sure what is happening in your code.
Update your method as :
// launch the application
public static boolean checkLogin(String username, String password)
throws SQLException {
System.out.print("dfdF");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
// connect to database usernames and query database
try {
// establish connection to database
Class.forName("com.mysql.jdbc.Driver").newInstance();
Connection con = DriverManager.getConnection(DATABASE_URL, "root", "root");
// query database
pt = con.prepareStatement("select userName,password from test.person where userName=?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery();
String orgUname = "", orPass = "";
while (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (orPass.equals(password)) {
//do something
return true;
rs.close();
} else {
//do something
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
And then update your user check as
try {
if(usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText())) {
System.out.println("User is validated");
} else {
return;
}
} catch (SQLException se) {
}

how to show output from console to JTextArea

I am beginner in Java Programming. How can i show my output from console to JTextArea. Here my code only show the output console. Anyone could tell or show me how can i do it.Thanks.
import java.sql.*;
public class Route
{
public void routeList()
{
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try
{
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url+dbName,userName,password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
while(result.next())
{
System.out.println(result.getString(1)+" "+result.getString(2));
}
conn.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
here is another file
import java.awt.FlowLayout;
import javax.swing.JFrame;
import javax.swing.JButton;
import javax.swing.JTextArea;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
public class GUI
{
public void createAndShowGUI()
{
JButton button2 = new JButton("Route");
//create a frame
JFrame frame = new JFrame("Yarra Tram Route Finder");
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLayout(new FlowLayout());
frame.add(button2);
button2.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent e)
{
//Execute when button is pressed
showNewFrame();
Route route = new Route();
route.routeList();
}
public void showNewFrame()
{
JFrame frame = new JFrame("Yarra Tram Route Finder (Route)" );
JTextArea textArea = new JTextArea();
frame.add(textArea);
frame.setSize(500,120);
frame.setLocationRelativeTo( null );
frame.setVisible( true );
textArea.setEditable( false );
}
});
frame.pack();
frame.setSize(350,100);
frame.setVisible(true);
}
}
Modified changes in your existing code. Check this
public class GUI extends JFrame {
JButton button2;
JTextArea textArea;
public GUI() {
super("Yarra Tram Route Finder");
}
public void routeList() {
Connection conn = null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "YarraTram";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "abc123";
try {
Class.forName(driver).newInstance();
conn = DriverManager.getConnection(url + dbName, userName, password);
PreparedStatement statement = conn.prepareStatement("Select rid,route from route");
ResultSet result = statement.executeQuery();
StringBuilder strBuilder = new StringBuilder();
while (result.next()) {
strBuilder.append(result.getString(1)).append(" ").append(result.getString(2));
strBuilder.append("\n");
}
textArea.setText(strBuilder.toString());
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public void createAndShowGUI() {
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setLayout(new FlowLayout());
button2 = new JButton("Route");
textArea = new JTextArea(20, 20);
add(textArea);
add(button2);
button2.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
routeList();
}
});
pack();
setVisible(true);
}
public static void main(String[] args) {
SwingUtilities.invokeLater(new Runnable() {
#Override
public void run() {
GUI gui = new GUI();
gui.createAndShowGUI();
}
});
}
}

My Java Swing Log in Form won't work

I finally got the password, the queries, the button and the connection, but how come it Seems I can't seem to log in? what's wrong with my Action Handler? please check my code
import java.awt.BorderLayout;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import javax.swing.JFrame;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JPanel;
import java.sql.*;
public class Login extends JFrame {
private JLabel label1, label2;
private JButton submit;
private JTextField textfield1;
private JPasswordField passfield;
private JPanel panel;
public Login() {
setSize(300, 100);
setVisible(true);
label1 = new JLabel("User ID:");
textfield1 = new JTextField(15);
label2 = new JLabel("Password:");
passfield = new JPasswordField(15);
submit = new JButton("Submit");
panel = new JPanel(new GridLayout(3, 1));
panel.add(label1);
panel.add(textfield1);
panel.add(label2);
panel.add(passfield);
panel.add(submit);
add(panel, BorderLayout.CENTER);
ButtonHandler handler = new ButtonHandler();
submit.addActionListener(handler);
}// end login constructor
private class ButtonHandler implements ActionListener {
public void actionPerformed(ActionEvent arg0) {
String user = textfield1.getText();
char[] passChars = passfield.getPassword();
Connection conn = Jdbc.dbConn();
PreparedStatement ps = null;
ResultSet rs = null;
String pass = new String(passChars);
if (passChars != null) {
String sql = "SELECT employee_ID,employee_password FROM user where" +
"employee_ID='user' and employee_password=+'pass'";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
user = rs.getString("employee_id");
pass = rs.getString("employee_password");
JOptionPane.showMessageDialog(null,"Welcome "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
}
}
}// end actionPerformed
}// End ButtonHandler
}// End of class
}
you have two choices for PreparedStatement, both are correct
1) change String sql = .... definition
String sql = "SELECT employee_ID, employee_password FROM
user WHERE employee_ID = ? AND employee_password = ?";
2) put variables to the SQL statement directly
String sql = "SELECT employee_ID, employee_password FROM user WHERE
employee_ID = '" + user + "' AND employee_password = '" + pass + "'";
Change your select
employee_ID=? and employee_password=?
http://www.javaworld.com/javaworld/jw-04-2007/jw-04-jdbc.html
Or you can use named parameters
String query = "select * from people where (first_name = :name or last_name
= :name) and address = :address");
NamedParameterStatement p = new NamedParameterStatement(con, query);
p.setString("name", name);
p.setString("address", address);
please rewrite your code like this
if (passChars != null) {
String sql = "SELECT employee_ID,employee_password FROM user where
employee_ID=? and employee_password=?";
try {
ps = conn.prepareStatement(sql);
ps.setString(1, user);
ps.setString(2, pass);
rs = ps.executeQuery();
if (rs.next()) {
user = rs.getString("employee_id");
pass = rs.getString("employee_password");
JOptionPane.showMessageDialog(null,"Welcome "+user);
} else {
JOptionPane.showMessageDialog(null, "Wrong Input");
}
} catch (Exception e) {
} finally {
try {
rs.close();
ps.close();
conn.close();
} catch (Exception ee) {
}
}
}

Categories