Saya baru mengenal JAVA, dan mencoba membuat formulir login dan registrasi yang terhubung ke database lokal MySQL. Saya telah mencari banyak instruksi untuk menghubungkan JAVA saya ke MySQL, tetapi berakhir dengan kesalahan. Saya pikir saya memiliki beberapa masalah dengan metode actionEvent() dan actionPerformed(ActionEvent e). Saya ingin membuatnya seperti ketika saya mendaftar akun baru, saya ingin menyimpan data pengguna itu ke database lokal MySQL. Dapatkah seseorang membantu saya untuk memecahkan masalah saya? Ini kode JAVA saya.

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");
    }
}
}

Ini kode MySQL saya:

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

Tolong beritahu saya, jika saya melakukan sesuatu yang salah. Terima kasih! 🙏

0
TSK 1 Juli 2020, 02:38

1 menjawab

Jawaban Terbaik

Anda melewatkan baris Class.forName("com.mysql.jdbc.Driver");

Untuk baris ("jdbc:mysql://localhost:3306/myDatabase","root", "root"), Anda harus memeriksa apakah sandinya adalah root. jika tidak ada kata sandi, maka harus seperti ini:

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();
        }
}
0
Ridwan 1 Juli 2020, 07:19