I'm new to JAVA, and trying to build a login and registration form which connected to MySQL local database. I've searched many instructions to connect my JAVA to MySQL, but it ends up with error. I think I have some problem with actionEvent() and actionPerformed(ActionEvent e) methods. I want to make it like when I register a new account, I want to save that user data into MySQL local database. Can someone help me to solve my problem? Here is my JAVA coding.
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.sql.*;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
// frame
JFrame frame;
// Options of position input
String[] position = {"Admin", "Manager", "Assistant"};
// inputs
JTextField firstName = new JTextField();
JTextField lastName = new JTextField();
JTextField userName = new JTextField();
JTextField email = new JTextField();
JPasswordField password = new JPasswordField();
JPasswordField confirmPW = new JPasswordField();
JComboBox positionComboBox = new JComboBox(position);
// labels
JLabel firstnameLabel = new JLabel("First Name");
JLabel lastnameLabel = new JLabel("Last Name");
JLabel usernameLabel = new JLabel("User Name");
JLabel passwordLabel = new JLabel("Password");
JLabel confirmPWLabel = new JLabel("Re-Password");
JLabel emailLabel = new JLabel("Email");
JLabel positionLabel = new JLabel("Position");
JLabel returnLoginLabel = new JLabel("Return to Login Page");
// buttons
JButton registerButton = new JButton("Register");
JButton cancelButton = new JButton("Cancel");
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
actionPerformed(null);
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
frame.setVisible(true);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: emailLabel
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
positionComboBox.setBounds(145, 340, 210, 32);
panel.add(positionComboBox);
// label: first name
firstnameLabel.setBounds(36, 84, 85, 16);
panel.add(firstnameLabel);
// label: last name
lastnameLabel.setBounds(36, 128, 85, 16);
panel.add(lastnameLabel);
// label: user name
usernameLabel.setBounds(36, 172, 85, 16);
panel.add(usernameLabel);
// label: password
passwordLabel.setBounds(36, 216, 85, 16);
panel.add(passwordLabel);
// label: re-password
confirmPWLabel.setBounds(36, 260, 85, 16);
panel.add(confirmPWLabel);
// label: emailLabel
emailLabel.setBounds(36, 304, 85, 16);
panel.add(emailLabel);
// label: position
positionLabel.setBounds(36, 347, 101, 16);
panel.add(positionLabel);
// Label: create a new account
returnLoginLabel.setBounds(182, 450, 138, 16);
panel.add(returnLoginLabel);
returnLoginLabel.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
frame.setVisible(false);
new LoginPage();
}
});
// button: cancel
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource() == registerButton) {
try {
//Creating Connection Object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement = connection.prepareStatement("insert into user values(?,?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, positionComboBox.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equals(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
// go back to login page if registered successfully
frame.setVisible(false);
new LoginPage();
}
else {
JOptionPane.showMessageDialog(null, "Password did not match");
// Clearing confirm password fields
confirmPW.setText("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (e.getSource() == cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
positionComboBox.setSelectedItem("Admin");
}
}
}
Here is my MySQL coding:
create database myDatabase;
use myDatabase;
create table user(
FIRSTNAME varchar(20),
LASTNAME varchar(20),
USERNAME varchar(20) not null,
PASSWRD varchar(20),
CONFIRMPASSWORD varchar(20),
EMAIL varchar(20),
POSITION varchar(20) );
Please tell me, if I'm doing anything wrong. Thank you! 🙏
You missed the line Class.forName("com.mysql.jdbc.Driver");
For the line ("jdbc:mysql://localhost:3306/myDatabase","root", "root"), you should check if the password is root. if there is no password, then it should be like this:
if (e.getSource() == registerButton) {
try {
Class.forName("com.mysql.jdbc.Driver");
//Creating Connection Object
Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "");
//Prepared Statement
PreparedStatement Pstatement = connection.prepareStatement("insert into user values(?,?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, positionComboBox.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equals(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
// go back to login page if registered successfully
frame.setVisible(false);
new LoginPage();
}
else {
JOptionPane.showMessageDialog(null, "Password did not match");
// Clearing confirm password fields
confirmPW.setText("");
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
Related
I have two JFrame windows one for the login and the second for the welcome. Now I want to present the Firstname and the Lastname of the connected user near to the hello in the welcome screen.
I tried many things but none of them worked so I'm asking for you help. I just started to learn GUI:
The login code:
import java.awt.EventQueue;
import java.sql.*;
import javax.swing.*;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class Login {
private JFrame frame;
private JLabel MainLogo;
String Firstname=null;
String Lastname=null;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login window = new Login();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
Connection connected = null;
private JTextField UsernameFiled;
private JPasswordField passwordField;
public Login() {
initialize();
connected = DBConnection.DBconnector();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 560, 256);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel lblNewLabel = new JLabel("UserName: ");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 20));
lblNewLabel.setBounds(160, 11, 140, 50);
frame.getContentPane().add(lblNewLabel);
JLabel lblPassword = new JLabel("PassWord: ");
lblPassword.setFont(new Font("Tahoma", Font.BOLD, 20));
lblPassword.setBounds(160, 72, 140, 40);
frame.getContentPane().add(lblPassword);
JButton Loginbtn = new JButton("Login");
Loginbtn.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select * from Users where nickname=? and password=?";
PreparedStatement pst = connected.prepareStatement(query);
pst.setString(1, UsernameFiled.getText());
pst.setString(2, passwordField.getText());
ResultSet res = pst.executeQuery();
Firstname = res.getString("Firstname");
Lastname = res.getString("Lastname");
int c=0;
while(res.next()) {
c++;
}
if(c == 0) {
JOptionPane.showMessageDialog(null, "You didnt put any username or password!");
}
else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage();
UserFrame.setVisible(true);
}else if( c > 1) {
JOptionPane.showMessageDialog(null, "Duplicate Username and Password");
}else {
JOptionPane.showMessageDialog(null, "Username and Password are inncorect...Try agian!");
}
pst.close();
res.close();
}catch(Exception LoginError) {
JOptionPane.showMessageDialog(null, LoginError);
}
}
});
Loginbtn.setFont(new Font("Tahoma", Font.BOLD, 20));
Loginbtn.setBounds(160, 148, 186, 40);
frame.getContentPane().add(Loginbtn);
UsernameFiled = new JTextField();
UsernameFiled.setFont(new Font("Tahoma", Font.BOLD, 16));
UsernameFiled.setBounds(310, 28, 186, 25);
frame.getContentPane().add(UsernameFiled);
UsernameFiled.setColumns(10);
passwordField = new JPasswordField();
passwordField.setFont(new Font("Tahoma", Font.BOLD, 16));
passwordField.setBounds(310, 84, 186, 25);
frame.getContentPane().add(passwordField);
MainLogo = new JLabel("");
Image imgs = new ImageIcon(this.getClass().getResource("/login.png")).getImage();
MainLogo.setIcon(new ImageIcon(imgs));
MainLogo.setBounds(10, 11, 128, 128);
frame.getContentPane().add(MainLogo);
}
}
The Welcome Code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import net.proteanit.sql.DbUtils;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.awt.Font;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import javax.swing.*;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class UserPage extends JFrame {
private JPanel contentPane;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
UserPage frame = new UserPage();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connected=null;
private JTable table;
public UserPage() {
connected=DBConnection.DBPreconnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 576, 410);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton bntLoadData = new JButton("Show Users Data");
bntLoadData.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "Select ID,Age,Password,Firstname,Lastname from users";
PreparedStatement pst = connected.prepareStatement(query);
ResultSet res = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(res));
} catch (Exception Error) {
Error.printStackTrace();
}
}
});
JLabel lblNewLabel = new JLabel("Hello, " + "The Username name");
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 18));
lblNewLabel.setBounds(10, 11, 280, 19);
contentPane.add(lblNewLabel);
bntLoadData.setFont(new Font("Tahoma", Font.BOLD, 20));
bntLoadData.setBounds(162, 102, 238, 23);
contentPane.add(bntLoadData);
table = new JTable();
table.setBounds(28, 136, 508, 221);
contentPane.add(table);
}
}
In your code, you does not seem to load the username or password of the logged in user at the welcome frame. Either you will have to pass that from the login frame or you will have to re-query the database and get firstname and lastname.
I suggest, simply pass the firstname and lastname from welcome screen via constructor.
In successful login, simply pass the name in the constructor: Login code addition:
} else if(c == 1) {
JOptionPane.showMessageDialog(null, "Hello to you, " + Firstname +" "+ Lastname);
frame.dispose();
UserPage UserFrame = new UserPage( Firstname, Lastname );
UserFrame.setVisible(true);
}
In the welcome frame, add a constructor to handle this:
public UserPage(String loggedInFirstName, String loggedInLastName){
// your remaining code
JLabel lblNewLabel = new JLabel("Hello, " + loggedInFirstName + " " + loggedInLastName );
// your remaining code.
}
A approach like this might work for your case and don't forget to mark the answer as accepted if this works for you
so I am using eclipse and mysql to create a login interface. The interface worked fine as a shell, so without being connected to the databse, and now I finally got it connected to the database but I'm running into the problem of linking it to another application upon successful login.
So for the shell of it I just gave the code a single username/password combo to proceed to the next part of the interface, but if I want to have the link work upon successful login in general, where do I place it in the code?
My code:
package project_files;
import javax.swing.JFrame;
import javax.swing.JToolBar;
import project_files.registration_test;
import project_files.root_login;
import project_files.gui_interface;
import project_files.video_interface;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JLabel;
import javax.swing.JTextField;
import javax.swing.JTextPane;
import javax.swing.JPasswordField;
import javax.swing.JButton;
import javax.swing.JSeparator;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
public class login_sys {
private JFrame frame;
private JTextField txtUsername;
private JPasswordField txtPassword;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
login_sys window = new login_sys();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public login_sys() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(200, 200, 523, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JLabel LabelLogin = new JLabel("Login Page");
LabelLogin.setBounds(209, 12, 100, 15);
frame.getContentPane().add(LabelLogin);
JLabel LabelUsername = new JLabel("Username");
LabelUsername.setBounds(61, 68, 92, 17);
frame.getContentPane().add(LabelUsername);
JLabel LabelPassword = new JLabel("Password");
LabelPassword.setBounds(61, 133, 66, 15);
frame.getContentPane().add(LabelPassword);
txtUsername = new JTextField();
txtUsername.setBounds(244, 68, 124, 19);
frame.getContentPane().add(txtUsername);
txtUsername.setColumns(10);
txtPassword = new JPasswordField();
txtPassword.setBounds(244, 131, 124, 19);
frame.getContentPane().add(txtPassword);
JButton btnLogin = new JButton("Login");
btnLogin.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/userdatabase", "root", "pass1234");
Statement stmt= con.createStatement();
String sql = "Select * from user where Email = '" +txtUsername.getText()+"' and Password ='" +txtPassword.getText().toString()+"'";
ResultSet rs=stmt.executeQuery(sql);
if(rs.next())
JOptionPane.showMessageDialog(null, "Login Successfully...");
else
JOptionPane.showMessageDialog(null, "Incorrect username and password...");
con.close();
} catch(Exception e) {System.out.print (e);}
String password = txtPassword.getText();
String username = txtUsername.getText();
if(password.contains("pass1234") && username.contains("root")){
txtPassword.setText(null);
txtUsername.setText(null);
root_login info = new root_login();
root_login.main(null);
}
else
{
if(password.contains("pass1234") && username.contains("john#gmail.com")){
txtPassword.setText(null);
txtUsername.setText(null);
JOptionPane.showMessageDialog(null, "Login Successful", "Login Warning", JOptionPane.WARNING_MESSAGE);
video_interface info = new video_interface();
video_interface.main(null);
}
else
{
JOptionPane.showMessageDialog(null, "Invalid Login Details", "Login Error", JOptionPane.ERROR_MESSAGE);
txtPassword.setText(null);
txtUsername.setText(null);
}
}
}});
btnLogin.setBounds(23, 203, 130, 25);
frame.getContentPane().add(btnLogin);
JButton btnReset = new JButton("Reset");
btnReset.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
txtUsername.setText(null);
txtPassword.setText(null);
}
});
btnReset.setBounds(212, 203, 114, 25);
frame.getContentPane().add(btnReset);
JButton btnNewExit = new JButton("Exit");
btnNewExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JFrame frmLogin_sys = new JFrame("Exit");
if (JOptionPane.showConfirmDialog(frmLogin_sys, "Confirm if you want to exit", "Login System",
JOptionPane.YES_NO_OPTION)== JOptionPane.YES_NO_OPTION) {
System.exit(0);
}
}
});
btnNewExit.setBounds(373, 203, 114, 25);
frame.getContentPane().add(btnNewExit);
JSeparator separator = new JSeparator();
separator.setBounds(12, 175, 499, 2);
frame.getContentPane().add(separator);
JSeparator separator_1 = new JSeparator();
separator_1.setBounds(12, 36, 499, 2);
frame.getContentPane().add(separator_1);
JButton btnCreateAccount = new JButton("Create Account");
btnCreateAccount.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
registration_test info = new registration_test();
registration_test.main(null);
}
});
btnCreateAccount.setBounds(135, 233, 265, 25);
frame.getContentPane().add(btnCreateAccount);
}
}
I was using (and it is still in my code currently)
if(password.contains("pass1234") && username.contains("john#gmail.com")){
txtPassword.setText(null);
txtUsername.setText(null);
JOptionPane.showMessageDialog(null, "Login Successful", "Login Warning", JOptionPane.WARNING_MESSAGE);
video_interface info = new video_interface();
video_interface.main(null);
to link a successful login to an additional application interface. Can i just
use
video_interface info = new video_interface();
video_interface.main(null);
as I have been doing? Where is the correct place to add this code? The second application location is imported at the beginning of my code.
If you change the constructor of the video_interface class to initialize and show the GUI components (as you're currently doing in the login_sys.initialize method), you'll be just fine with
video_interface info = new video_interface()
There should only be one static void main(String[] args) method in any Java program.
As a side note, Java conventionally uses camelCasing, (e.g. JFrame, JTextField) and if you adopt that convention your code will be easier to read.
I have a simple program that takes in info for a car sale and enters it in the MySQL DB, everything inserts 100% properly, except the commission integer. It constantly inserts a constant number, never the 'comm' value I have it set to enter. I have the print statement show the correct value but when i check the DB it's not the correct value. I'm not sure if there's a bug on my end or a JDBC thing?
I've entered a simple value of 1, the print statement reads one but the db will always show a value like 1400.
Image links: https://imgur.com/apuKB0C https://imgur.com/Kijl9yL
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import java.util.Random;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Statement;
import java.awt.event.ActionEvent;
public class Sale {
Connection con;
Statement st;
int rs;
ResultSet rs1;
ResultSet rs2;
boolean rs3;
JFrame frame5;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_3;
private JTextField textField_4;
private JTextField textField_5;
private JTextField textField_6;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Sale window = new Sale();
window.frame5.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public void connect() {
try {
Class.forName("com.mysql.cj.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/project", "root", "Alesana14");
st = con.createStatement();
} catch (Exception ex) {
}
}
/**
* Create the application.
*/
public Sale() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame5 = new JFrame();
frame5.setBounds(100, 100, 834, 543);
frame5.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame5.getContentPane().setLayout(null);
JLabel lblCreateSale = new JLabel("Create Sale");
lblCreateSale.setFont(new Font("Lucida Grande", Font.PLAIN, 20));
lblCreateSale.setBounds(385, 113, 110, 44);
frame5.getContentPane().add(lblCreateSale);
JLabel label_1 = new JLabel("Model:");
label_1.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_1.setBounds(264, 252, 77, 16);
frame5.getContentPane().add(label_1);
JLabel label_2 = new JLabel("Make:");
label_2.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_2.setBounds(264, 214, 77, 16);
frame5.getContentPane().add(label_2);
JLabel label_4 = new JLabel("Price:");
label_4.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_4.setBounds(264, 294, 77, 16);
frame5.getContentPane().add(label_4);
JLabel label_5 = new JLabel("Color:");
label_5.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_5.setBounds(264, 336, 77, 16);
frame5.getContentPane().add(label_5);
textField = new JTextField();
textField.setColumns(10);
textField.setBounds(353, 210, 185, 26);
frame5.getContentPane().add(textField);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(353, 248, 185, 26);
frame5.getContentPane().add(textField_1);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(353, 284, 185, 26);
frame5.getContentPane().add(textField_3);
JButton btnEnter = new JButton("Enter");
btnEnter.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String id = textField_6.getText().trim();
String make = textField.getText().trim();
String model = textField_1.getText().trim();
String price = textField_3.getText().trim();
String color = textField_4.getText().trim();
String year = textField_5.getText().trim();
String sql = "UPDATE product SET inventory = inventory-1 WHERE make='" + make + "' and model = '"
+ model + "' and color ='" + color + "' and yearMade=" + year + "";
// executeUpdate for insert,delete, and update
PreparedStatement ps;
ps = Connectivity.getConnection().prepareStatement(sql);
rs = ps.executeUpdate();
String sql1 = "UPDATE employee SET commission = commission + (commissionRate*"+price+") WHERE id = "+id+"";
ps = Connectivity.getConnection().prepareStatement(sql1);
rs = ps.executeUpdate();
//inserts into sales
Random rand = new Random();
int random =rand.nextInt(999999);
String sql2 = "SELECT id FROM product WHERE make = '"+make+"' and model = '"+model+"' and color = '"+color+"' and yearMade = '"+year+"'";
st = Connectivity.getConnection().createStatement();
rs2 = st.executeQuery(sql2);
while(rs2.next()) {
int totalPrice = Integer.parseInt(price);
Double comm = totalPrice * .035;
int prodID = rs2.getInt("id");
String sql3 = "INSERT INTO sales VALUES('"+random+"','"+id+"','"+prodID+"','"+1+"','"+totalPrice+"',"+comm+")";
ps = Connectivity.getConnection().prepareStatement(sql3);
rs = ps.executeUpdate();
System.out.println(totalPrice);
System.out.println(comm);
System.out.println(ps);
}
JOptionPane.showMessageDialog(null, "Items Sold!");
}
catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnEnter.setBounds(423, 407, 130, 29);
frame5.getContentPane().add(btnEnter);
JButton button_1 = new JButton("Return to menu");
button_1.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Menu men = new Menu();
men.frame2.setVisible(true);
frame5.setVisible(false);
}
});
button_1.setBounds(266, 407, 145, 29);
frame5.getContentPane().add(button_1);
textField_4 = new JTextField();
textField_4.setColumns(10);
textField_4.setBounds(353, 326, 185, 26);
frame5.getContentPane().add(textField_4);
JLabel label_6 = new JLabel("Year:");
label_6.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
label_6.setBounds(264, 374, 77, 16);
frame5.getContentPane().add(label_6);
textField_5 = new JTextField();
textField_5.setColumns(10);
textField_5.setBounds(353, 364, 185, 26);
frame5.getContentPane().add(textField_5);
JLabel lblEmployeeId = new JLabel("Employee ID:\n\n");
lblEmployeeId.setFont(new Font("Lucida Grande", Font.PLAIN, 16));
lblEmployeeId.setBounds(245, 172, 121, 16);
frame5.getContentPane().add(lblEmployeeId);
textField_6 = new JTextField();
textField_6.setColumns(10);
textField_6.setBounds(353, 169, 185, 26);
frame5.getContentPane().add(textField_6);
JLabel imgLabel = new JLabel(new ImageIcon("/Users/jonathonmoreno/Desktop/Project/src/resize.png"));
imgLabel.setBounds(-11, 0, 845, 521);
frame5.getContentPane().add(imgLabel);
}
}
I'm new to using UCanAccess and Microsoft Access as a database for java:
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\decx\\Desktop\\Db.accdb");
String sql = "insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Tips & Tricks");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}
I need to get the code to send data when the submit button is clicked. This is a school project where I have to allow users to enter water usage and bill (water utility bill), so I can display it later.
I have ran the code previously and but errors like "unexpected token" or "user has no privilege or object not found".
There are some notes :
You get this error (unexpected token) because the names of columns and table should not be between two quotes ''
The + operator is not allow in that position of query
Also, only the Strings can be between two quotes not the ints, make sure the type of ID for example is a String, if not you have to remove the two quotes
Read about Prepared Statement to avoid syntax error and to prevent SQL Injection
Look at :
String sql="insert into db ('ID', 'WaterUsage', 'Bill') + values ('1', '12', '12')";
//(1)-----------------------^--^--^----------^--^----^ ^ ^ ^
//(2)___________________________________________________| | |
//(3)_____________________________________________________________| |
That helped me a lot and with the help of my friends i completed my code, for anyone who might need this at any point, i'll be including my code.
import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.*;
import net.ucanaccess.jdbc.*;
public class Memo extends JFrame implements ActionListener {
private JTextField textField;
private JTextField textField_1;
Connection cn = null;
ResultSet rs = null;
Statement s = null;
public Memo() {
getContentPane().setBackground(Color.DARK_GRAY);
getContentPane().setLayout(null);
textField = new JTextField();
textField.setBounds(246, 0, 178, 50);
getContentPane().add(textField);
textField.setColumns(10);
JLabel lblNewLabel = new JLabel("Enter bill amount: $");
lblNewLabel.setFont(new Font("Arial Narrow", Font.BOLD, 11));
lblNewLabel.setForeground(Color.WHITE);
lblNewLabel.setBounds(10, 0, 237, 50);
getContentPane().add(lblNewLabel);
JLabel label = new JLabel("Enter water usage amount(l): ");
label.setFont(new Font("Arial Narrow", Font.BOLD, 11));
label.setForeground(Color.WHITE);
label.setBounds(10, 49, 237, 50);
getContentPane().add(label);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(246, 49, 178, 50);
getContentPane().add(textField_1);
JButton btnSubmit = new JButton("Submit");
btnSubmit.addMouseListener(new MouseAdapter() {
public void mouseClicked(MouseEvent e) {
try {
int num = Integer.parseInt(textField.getText());
int num1 = Integer.parseInt(textField_1.getText());
textField.getText();
textField_1.getText();
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");
Connection cn = DriverManager.getConnection("jdbc:ucanaccess://C:\\Users\\DECX\\Desktop\\Db.accdb");
String sql = "insert into db (WaterUsage, Bill) values ('"+num+"', '"+num1+"')";
s = cn.createStatement();
s.executeUpdate(sql);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
});
btnSubmit.setFont(new Font("Arial Narrow", Font.BOLD, 11));
btnSubmit.setBounds(272, 131, 141, 35);
getContentPane().add(btnSubmit);
}
public static void main(String[] args) throws Exception {
Memo qMemo = new Memo();
qMemo.setSize(500, 350);
qMemo.setVisible(true);
qMemo.setTitle("Memo");
qMemo.setDefaultCloseOperation(EXIT_ON_CLOSE);
qMemo.getContentPane().setLayout(null);
}
public void actionPerformed(ActionEvent e) {
}
}
I am developing a basic program that has 3 JFrames. A log-in, a registration and a Dashboard to be opened after successful log-in attempt. However, I am getting an error after typing in the username and password and clicking log-in button.
Here's the error:
com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ' password='1234'' at line 1
And here's my code:
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.border.EmptyBorder;
import com.mysql.jdbc.Statement;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.ImageIcon;
import java.awt.Font;
import javax.swing.JTextField;
import javax.swing.JButton;
import java.awt.event.ActionListener;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.awt.event.ActionEvent;
public class Login extends JFrame {
private JPanel contentPane;
private JTextField txtUsrName;
private JTextField txtPAss;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Login() {
setDefaultCloseOperation(JFrame.HIDE_ON_CLOSE);
setBounds(100, 100, 450, 348);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblLogin = new JLabel("Welcome To TechApp");
lblLogin.setFont(new Font("Tekton Pro", Font.PLAIN, 18));
lblLogin.setBounds(135, 19, 163, 28);
contentPane.add(lblLogin);
JLabel lblUsername = new JLabel("UserName:");
lblUsername.setFont(new Font("Alaska", Font.PLAIN, 15));
lblUsername.setBounds(174, 58, 88, 28);
contentPane.add(lblUsername);
txtUsrName = new JTextField();
txtUsrName.setBounds(145, 90, 132, 20);
contentPane.add(txtUsrName);
txtUsrName.setColumns(10);
JLabel lblPassword = new JLabel("Password:");
lblPassword.setFont(new Font("Alaska", Font.PLAIN, 15));
lblPassword.setBounds(182, 118, 95, 46);
contentPane.add(lblPassword);
txtPAss = new JTextField();
txtPAss.setColumns(10);
txtPAss.setBounds(145, 156, 132, 20);
contentPane.add(txtPAss);
JButton btnNewButton = new JButton("login");
btnNewButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String _username = txtUsrName.getText();
String _password = txtPAss.getText();
String url = "jdbc:mysql://127.0.0.1:3306/javabase";
String user = "java";
String passw = "password";
try{
// 1.Get a connection To Database
Connection myConn = DriverManager.getConnection(url, user, passw);
// 2.Create a statement
Statement myStmt = (Statement) myConn.createStatement();
// 3.Execute SQL Query
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"', password='"+_password+"' ";
ResultSet result = myStmt.executeQuery(sql);
//myStmt.executeUpdate(sql);
int count = 0;
while(result.next()){
count = count + 1;
}
if(count == 1){
Dashboard frame = new Dashboard();
frame.setVisible(true);
}
else if(count > 1){
JOptionPane.showMessageDialog(null, "Duplicate User! Access Denied!");
}
else{
JOptionPane.showMessageDialog(null, "User Not Found!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnNewButton.setBounds(169, 202, 89, 49);
contentPane.add(btnNewButton);
JButton btnRegister = new JButton("Register");
btnRegister.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Main frame = new Main();
frame.setVisible(true);
}
});
btnRegister.setBounds(168, 264, 89, 23);
contentPane.add(btnRegister);
JLabel lblNewLabel = new JLabel("");
lblNewLabel.setFont(new Font("Alaska", Font.PLAIN, 16));
lblNewLabel.setIcon(new ImageIcon("D:\\ExploitGate\\MAS-9831-Offwhite2.jpg"));
lblNewLabel.setBounds(0, 0, 434, 310);
contentPane.add(lblNewLabel);
}
}
I've searched the stackoverflow forum and carried out the possible solution given here
Can anyone please guide me how to handle this error?
Thanks In Advance :)
All of the above code is basically useless. It's an SQL syntax error, which means it's this one line:
... WHERE userame='"+_username+"', password='"+_password+"' ";
^---
you don't use , to separate where clause arguments. You use boolean operations. and, or, etc...
And note that you're vulnerable to sql injection attacks
You were using a comma , between your WHERE clauses rather than an AND.
String sql = "SELECT userame, password FROM registration WHERE userame='"+_username+"' AND password='"+_password+"' ";