JAVA jframe.remove(panel) doesn't work as expected - java

I have a Jframe with two panels and i am trying to change the panels/views using jmenu items.
The first panel adds data to a database. User can then switch to the view panel by clicking the JMenuBarItem.
The Second panel fetches data from the database and displays the results in a JTable.
Everything works fine but when i switch back and forth to the second panel it adds another panel instead of removing it/replacing it. See linked images below to better understand
First Panel
Second Panel
Second Panel after switching back and forth
package employeerecords3;
import java.awt.*;
import java.awt.event.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.ArrayList;
import javax.swing.*;
public class EmployeeRecords3 extends JFrame {
JLabel empnolb, empnamelb, empdptlb, basicsallb, hseallowancelb;
JTextField empnotf, empnametf, empdpttf, basicsaltf, hseallowancetf;
JButton submitbtn, cancelbtn;
String host = "jdbc:mysql://localhost:3306/employee";
String username = "root";
String password = "";
EmployeeRecords3() {
setTitle("Employee Records");
final JPanel addpanel = new JPanel();
final JPanel viewpanel = new JPanel();
setTitle("Employee Records");
JMenuBar menubar = new JMenuBar();
setJMenuBar(menubar);
JMenu file = new JMenu("File");
menubar.add(file);
JMenuItem add = new JMenuItem("Add Employee");
JMenuItem view = new JMenuItem("View Employees");
file.add(add);
file.add(view);
add.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
if (viewpanel.isShowing()) {
remove(viewpanel);
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department", "Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF", "Pension", "NetPay"};
try {
String query = "SELECT * FROM payroll";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
ResultSet rs = st.executeQuery(query);
while (rs.next()) {
String[] results = {rs.getString(1), rs.getString(2), rs.getString(3), Double.toString(rs.getDouble(4)), Double.toString(rs.getDouble(5)), Double.toString(rs.getDouble(6)), Double.toString(rs.getDouble(7)), Double.toString(rs.getDouble(8)), Double.toString(rs.getDouble(9)), Double.toString(rs.getDouble(10))};
datalist.add(results);
}
con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
} catch (Exception ex) {
ex.printStackTrace();
}
if (addpanel.isShowing()) {
remove(addpanel);
add(viewpanel);
} else if (viewpanel.isShowing()) {
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
empnolb = new JLabel("Emp No");
empnamelb = new JLabel("Name");
empdptlb = new JLabel("Department");
basicsallb = new JLabel("Basic Pay");
hseallowancelb = new JLabel("House Allowance");
empnotf = new JTextField();
empnametf = new JTextField();
empdpttf = new JTextField();
basicsaltf = new JTextField();
hseallowancetf = new JTextField();
submitbtn = new JButton("Submit");
cancelbtn = new JButton("Cancel");
Submit submithandler = new Submit();
submitbtn.addActionListener(submithandler);
Cancel cancelhandler = new Cancel();
cancelbtn.addActionListener(cancelhandler);
addpanel.add(empnolb);
addpanel.add(empnotf);
addpanel.add(empnamelb);
addpanel.add(empnametf);
addpanel.add(empdptlb);
addpanel.add(empdpttf);
addpanel.add(basicsallb);
addpanel.add(basicsaltf);
addpanel.add(hseallowancelb);
addpanel.add(hseallowancetf);
addpanel.add(submitbtn);
addpanel.add(cancelbtn);
addpanel.setLayout(new GridLayout(6, 2));
viewpanel.setLayout(new GridLayout(1, 1));
add(addpanel);
setSize(300, 400);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setVisible(true);
}
private class Submit implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
String empNo, empName, department;
double grossPay, basicPay, hseAllowance, payee, nhif, nssf, pension, netPay;
empNo = empnotf.getText();
empName = empnametf.getText();
department = empdpttf.getText();
basicPay = Double.parseDouble(basicsaltf.getText());
hseAllowance = Double.parseDouble(hseallowancetf.getText());
grossPay = basicPay + hseAllowance;
payee = 0.3 * grossPay;
if (grossPay > 100000) {
nhif = 1200;
} else {
nhif = 320;
}
nssf = 200;
pension = 0.05 * basicPay;
netPay = grossPay - (payee - nhif - nssf - pension);
String query = "INSERT INTO payroll(EmpID,EmpName,Department,BasicPay,HouseAllowance,Payee,NHIF,NSSF,Pension,NetPay) VALUES('" + empNo + "','" + empName + "','" + department + "','" + basicPay + "','" + hseAllowance + "','" + payee + "','" + nhif + "','" + nssf + "','" + pension + "','" + netPay + "')";
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(host, username, password);
Statement st = con.prepareStatement(query);
int count = st.executeUpdate(query);
boolean action = (count > 0);
if (action) {
empnotf.setText(null);
empnametf.setText(null);
empdpttf.setText(null);
basicsaltf.setText(null);
hseallowancetf.setText(null);
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
private class Cancel implements ActionListener {
#Override
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
}
public static void main(String[] args) {
EmployeeRecords3 er = new EmployeeRecords3();
}
}

The mistake you made is that you create a new JTable every time you open the viewpanel. You not only create a new one, you add it to your view-JPanel. This is why you get the weird behaviour.
This code snippet fixes your problem. I just added the removeAll() method call to the add-JPanel ActionListener. When the add-JPanel is opened, the old JTable is removed from the view-JPanel. I had to comment out your database interactions.
// ...
// ...
// ...
add.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
if (viewpanel.isShowing())
{
remove(viewpanel);
/*
* I basically just added this one line.
* Since you want to make a fresh query after
* you come back to the viewpanel, we can delete
* all the elements (which is only the JTable).
*/
viewpanel.removeAll();
add(addpanel);
}
revalidate();
repaint();
}
});
view.addActionListener(new ActionListener()
{
public void actionPerformed(ActionEvent ae)
{
java.util.List<String[]> datalist = new ArrayList<>();
String[] columnNames = {"Emp ID", "Emp Name", "Department",
"Basic Pay", "House Allowance", "Payee", "NHIF", "NSSF",
"Pension", "NetPay"};
try
{
// String query = "SELECT * FROM payroll";
// Class.forName("com.mysql.jdbc.Driver");
// Connection con = DriverManager.getConnection(host, username,
// password);
// Statement st = con.prepareStatement(query);
// ResultSet rs = st.executeQuery(query);
String[] results = {"a", "b", "c", "d", "e", "f", "g", "h",
"i", "j"};
datalist.add(results);
// con.close();
String[][] data = new String[datalist.size()][];
data = datalist.toArray(data);
JTable table = new JTable(data, columnNames);
JScrollPane sp = new JScrollPane(table);
viewpanel.add(sp);
}
catch (Exception ex)
{
ex.printStackTrace();
}
if (addpanel.isShowing())
{
remove(addpanel);
add(viewpanel);
}
else if (viewpanel.isShowing())
{
remove(viewpanel);
add(viewpanel);
}
revalidate();
repaint();
}
});
// ...
// ...
// ...
The solution on top is not the only one of course. I don't know where you wanna go with this UI, but you can just remove the contents of the table and refill them as soon as you open the view-JPanel again.
Another solution would be to remove the JTable specifically (but in this case you probably need to have it as a field, because you create the table in a block that you can't reference from your add.addActionListener-Block)
The third solution would be to add a boolean flag, that checks if the table has been loaded and only create a new JTable, if it hasn't.

Related

JTable doesn't update after SQL insert

I'm struggeling the whole day with a stupid problem. I insert with executeupdate a row in my database. I tried it with fireTableDataChanged, setModel and every hint i could find here.
But nothing changes. The data is inserted and only if i reopen my app i can see my insert.
I hope this class is enough to solve my problem. Otherwise i could paste my executeupdate statement or my mainclass.
I really hope you can help me.
Table
public TabelleErfasst()
{
super(new GridLayout(1, 0));
JTable table = new JTable();
table.setPreferredScrollableViewportSize(new Dimension(950, 300));
table.setFillsViewportHeight(true);
DefaultTableModel model = new DefaultTableModel();
model.setRowCount(0);
table.setModel(model);
Object[] columnsName = new Object[7];
columnsName[0] = "Vorname";
columnsName[1] = "Nachname";
columnsName[2] = "Straße";
columnsName[3] = "Stadt";
columnsName[4] = "Hat abgestimmt für";
columnsName[5] = "ID";
columnsName[6] = "Sterne";
model.setColumnIdentifiers(columnsName);
Object[] rowData = new Object[8];
ArrayList<Stimmzettel> stimmzettel = ErfasstDatabase.getStimmzettel();
for (int i = 0; i < stimmzettel.size(); i++) {
rowData[0] = stimmzettel.get(i).getVorName();
rowData[1] = stimmzettel.get(i).getNachName();
rowData[2] = stimmzettel.get(i).getStrasse();
rowData[3] = stimmzettel.get(i).getStadt();
rowData[4] = stimmzettel.get(i).getAbgestimmtFuer();
rowData[5] = stimmzettel.get(i).getProjektId();
rowData[6] = stimmzettel.get(i).getSterne();
model.addRow(rowData);
}
// Ändere Spaltenbreite, wenn i == 1 -> breiter
TableColumn column = null;
for (int i = 0; i < 7; i++) {
column = table.getColumnModel().getColumn(i);
if (i == 1) {
column.setPreferredWidth(150); //
} else if (i == 4) {
column.setPreferredWidth(200);
} else if (i == 5) {
column.setPreferredWidth(45);
} else if (i == 6) {
column.setPreferredWidth(45);
} else {
column.setPreferredWidth(150);
}
}
JScrollPane scrollPane = new JScrollPane(table);
add(scrollPane);
}
}
Statement
public class DBProjektController {
public void insert(String f1, String f2, String f3, String f4, String f5, String f6, String f7) {
if (f1.isEmpty()) {
System.out.println("The ID cannot be null!");
} else {
try {
Connection con;
con = DriverManager.getConnection("jdbc:ucanaccess://C:/Projekt/DB/erfasst.accdb");
Statement statement = con.createStatement();
statement.executeUpdate("INSERT INTO ERFASST(VORNAME, NAME, STRASSE, ORT, ABGESTIMMT_PROJEKT, PROJEKTID, STERNE) VALUES('" + f1 + "','" + f2 + "','" + f3 + "','" + f4 + "','" + f5 + "','" + f6 + "','" + f7 + "')");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
Snippet from my MainClass (I deleteted some parts that doesn't really concern my problem)
public class Gui extends JFrame {
/**
*
*/
private static final long serialVersionUID = 1L;
// Frame
JFrame frame = new JFrame();
// Erstelle JTabbedPane
JTabbedPane jtp = new JTabbedPane();
// Panel
JPanel panel = new JPanel();
public Gui() {
frame.getContentPane().add(jtp);
JPanel pAbstimmung = new JPanel(null);
TabelleErfasst tabelleErfasst = new TabelleErfasst();
tabelleErfasst.setSize(950, 350);
tabelleErfasst.setLocation(35, 80);
JButton bSterneExport = new JButton("Sterne exportieren");
bSterneExport.setSize(300, 60);
bSterneExport.setLocation(682, 480);
JButton bEintragNeu = new JButton("Ausgewählten Eintrag löschen");
bEintragNeu.setSize(300, 60);
bEintragNeu.setLocation(358, 480);
JButton bEintragLoeschen = new JButton("Alle Einträge löschen");
bEintragLoeschen.setSize(300, 60);
bEintragLoeschen.setLocation(35, 480);
JLabel lZettelSession = new JLabel("Alle eingetragenen Stimmzettel der aktuellen Session");
// Inhalte zu Abstimmungsergebnis
pAbstimmung.add(tabelleErfasst);
pAbstimmung.add(bEintragLoeschen);
pAbstimmung.add(bEintragNeu);
pAbstimmung.add(bSterneExport);
pAbstimmung.add(lZettelSession);
jtp.addTab("Abstimmungsergebnis", pAbstimmung);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
bStimmeKontrolle.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
new Thread(new Runnable() {
public void run() {
new DBProjektController().insert(erfasstVorname.getText(), erfasstNachname.getText(),
erfasstStrasse.getText(), erfasstStadt.getText(), projektAuswahl.getText(),
erfasstId.getText(), sterneGruppe.getSelection().getActionCommand());
}
}).start();
TabelleErfasst tabelleErfasst = new TabelleErfasst();
jtp.setSelectedIndex(3);
}
});
// Titel des Fensters
frame.setTitle("AfVF");
// Gr��e des Fensters
frame.setResizable(false);
frame.pack();
frame.setSize(1024, 650);
frame.setVisible(true);
}
}

get table names from DB and parse it to JCombobox and then when a tablename is select it should display the table info in the JTable

I need help with retrieving tableNames from my database and then parse it to JCombobox and the when the tableName is click the sql statement will be performed and then display the table in the JTable.
My problem is how to code the selectedItem so that it will execute the query and display IT on the JTable
Here is my gui.java file
package Assignment3.Live;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.Vector;
import javax.swing.*;
import javax.swing.border.TitledBorder;
import javax.swing.event.TableModelEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumn;
import javax.swing.table.TableColumnModel;
import javax.swing.table.TableModel;
import net.proteanit.sql.DbUtils;
;
/**
* #author jmickey
*
*/
public class GUI extends JFrame {
// Variables
public Main main;
DBCon db;
MakeTable make;
private JFrame frame = new JFrame();
private JPanel pNorth, pChooser, pdp, pRC, pSCR, pTab, pSouth, pBtn;
public ResultSet rseTo = null;// result set
public PreparedStatement pst = null;
private ResultSetMetaData meta = null;
String tableNamesnow = "";
private JMenuBar jMenuBar;
private JMenu file, help;
private JComboBox<String> jcmb = new JComboBox<String>();
ComboBoxModel<?> giveMeTableName = (ComboBoxModel<?>) jcmb
.getSelectedItem();
private JTable jT = new JTable();
private JTextArea text;
private JButton search, clear, displayRow, deletRow, addRow, query, save,
restore;
private JCheckBox rowS = new JCheckBox("Select by Rows", true);
private JCheckBox colS = new JCheckBox("Selcet by Column", false);
/*
* private String[] columnNames = {}; private Object [][] rowData = {};
*/
public GUI() throws SQLException {
GUInterface();
getTableNames();
arrayOfTable();
}
public void GUInterface() {// constructor
// Menubar
setLayout(new BorderLayout(5, 10));
jcmb.setSelectedItem("");
jMenuBar = new JMenuBar();
file = new JMenu("File");
file.add(new JMenuItem("Start"));
file.add(new JMenuItem("Exit"));
help = new JMenu("Help");
help.add(new JMenuItem("Help"));
jMenuBar.add(file);
jMenuBar.add(help);
// Button
save = new JButton("Save");
clear = new JButton("Clear");
restore = new JButton("Restore");
displayRow = new JButton("Display Row");
deletRow = new JButton("Delet Row");
addRow = new JButton("Add New Row");
query = new JButton("QUERY");
// choose table panel = 1
pChooser = new JPanel();
pChooser.setLayout(new BorderLayout(5, 0));
pChooser.setBorder(new TitledBorder("Tables"));
pChooser.add(new JLabel("Select a table: "), BorderLayout.WEST);
pChooser.add(jcmb, BorderLayout.CENTER);
// Row/Column selection Panel = 2
pRC = new JPanel();
pRC.setLayout(new FlowLayout(FlowLayout.LEFT));
pRC.add(rowS);
pRC.add(colS);
// noth panel holds (pChooser & pRC)
pNorth = new JPanel();
pNorth.setLayout(new GridLayout(2, 1));
pNorth.add(pChooser);
pNorth.add(pRC);
// JTable panel
pTab = new JPanel();
pTab.setLayout(new GridLayout(1, 1));
pTab.add(jT);
pTab.add(new JScrollPane(jT));
// display holds (pNorth & pTab)
pdp = new JPanel();
pdp.setLayout(new BorderLayout(2, 1));
pdp.add(pNorth, BorderLayout.NORTH);
pdp.add(pTab, BorderLayout.SOUTH);
// Save, Clear or restore Panel
pSCR = new JPanel();
pSCR.add(save);
pSCR.add(clear);
pSCR.add(restore);
// Button selection panel
pBtn = new JPanel();
pBtn.setLayout(new GridLayout(2, 2));
pBtn.add(displayRow);
pBtn.add(addRow);
pBtn.add(query);
pBtn.add(deletRow);
// South panel (pSCR & pBtn)
pSouth = new JPanel();
pSouth.setLayout(new BorderLayout(2, 1));
pSouth.add(pBtn, BorderLayout.SOUTH);
pSouth.add(pSCR, BorderLayout.CENTER);
// Table info
jT.setAutoResizeMode(jT.AUTO_RESIZE_OFF);
jT.setGridColor(Color.BLUE);
jT.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
jT.setSelectionBackground(Color.BLUE);
jT.setSelectionForeground(Color.WHITE);
jT.setRowSelectionAllowed(true);
/*
* Task 1. change action to diplay row = create the 2.delete row
* 3.insert row
*/
frame.setJMenuBar(jMenuBar);
frame.add(pdp, BorderLayout.NORTH);
frame.add(pSouth, BorderLayout.SOUTH);
frame.setTitle("Walters SPJ Directory");
frame.setResizable(true);
frame.setSize(465, 648);
frame.setLocationRelativeTo(null);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setVisible(true);
// display rows
displayRow.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
// when the search button is clicked
if (e.getSource() == displayRow) {
jcmb.setSelectedItem(giveMeTableName);
for (int i = 0; i < jcmb.getSelectedIndex(); i++)
displayS();
}
}
});
// Checkbos ActionListener
rowS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(rowS.isSelected());
}
});
colS.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
jT.setRowSelectionAllowed(colS.isSelected());
}
});
// Clear ActionListener
clear.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.tableChanged(null);
}
});
}
// get tableNames
public void getTableNames() throws SQLException {
rseTo = null;
java.sql.DatabaseMetaData meta = DBCon.con.getMetaData();
rseTo = meta.getTables(null, null, "%", new String[] { "TABLE" });
while (rseTo.next()) {
String nameOfTables = rseTo.getString(3);
String tableCatalog = rseTo.getString(1);
String tableSchema = rseTo.getString(2);
System.out.printf("%s - %s - %s%n", tableCatalog, tableSchema,
nameOfTables);
}
db.stm.close();
}
// get table name to JCombobox
public void arrayOfTable() throws SQLException {
rseTo = db.con.getMetaData().getTables(null, null, "%",
new String[] { "TABLE" });
while (rseTo.next()) {
String giveMeTableName = (rseTo.getString(3));
jcmb.addItem(giveMeTableName);
System.out.println(giveMeTableName);
}
jcmb.setBounds(130, 30, 190, 30);
jcmb.setEditable(false);
jcmb.getSelectedIndex();
return;
}
/*
* Table selection method
*/
public void displayS() {
try {
String sql = "SELECT DISTINCT * FROM " + giveMeTableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
TableModel myData = DbUtils.resultSetToTableModel(rseTo);
jT.setModel(myData);
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayP() {
try {
String sql = "SELECT DISTINCT * FROM P";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displayJ() {
try {
String sql = "SELECT DISTINCT * FROM " + make.tableName;
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
public void displaySPJ() {
try {
String sql = "SELECT DISTINCT * FROM SPJ";
pst = DBCon.con.prepareStatement(sql);
rseTo = pst.executeQuery();
jT.setModel(DbUtils.resultSetToTableModel(rseTo));
} catch (Exception ex) {
JOptionPane.showMessageDialog(null, ex);
}
}
}
For tasks like this, you need to be aware that you're developing a new (simple) programming language. This means the input is no longer free form but has to obey certain rules. For example:
Table name: S
...
Table name:
P
is bad. The people editing the file should stick to one way to specify the table name; otherwise your parser will quickly get complex.
As a general guideline for tasks like this:
Read the input line by line.
Ignore empty lines
Trim lines to get rid of excessive whitespace
Use patterns like Table name: together with line.startsWith() to find out what the next "block" of your language means.
Read the values of each block and process then. line.split("\\s", -1) is your friend to split the input into words.
Getting it right will become easier when you create a few simple test cases and use unit tests to make sure your parser builds the correct data structures in memory.

Can not issue data manipulation statements with executeQuery

I'm getting an error when im trying to run my gui to inset data into a table, the error being Can not issue data manipulation statements with executeQuery(). The goal of this gui is to get the user to input information into the text area and then click submit and this information is uploaded to the database.
error : java.sql.SQLException: Can not issue data manipulation statements with executeQuery().
my code is
class registerInterface extends JFrame {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/mysql";
static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
static final String USERNAME = "root";
static final String PASSWORD = "root";
private JTextField jtfFname, jtfLname, jtfAddress1, jtfAddress2, jtfCity, jtfZipcode, jtfState, jtfUsername, jtfPassword, jtfPassConfirm, jtfEmail, jtfdtype;
private JButton exitButton, backButton, clearButton, submitButton;
private JMenuItem jmiBack, jmiClear, jmiSubmit, jmiExit, jmiHelp, jmiAbout;
String first, last, email, address, username, password, dtype;
// launch the application
public void Create() {
Connection conn = null;
try {
Class.forName(JDBC_DRIVER).newInstance();
conn = DriverManager.getConnection(DATABASE_URL, USERNAME, PASSWORD);
PreparedStatement statement = conn.prepareStatement("INSERT INTO person ('firstName', 'lastName', 'email', 'address', 'userName', 'password', 'dtype') "
+ "VALUES ('" + first + "', '" + last + "', '" + email + "', '" + address + "', '" + username + "', '" + password + "', '" + dtype + "')");
statement.executeQuery();
} catch (Exception e) {
e.printStackTrace();
}
}
registerInterface() {
//create menu bar
JMenuBar regMenuBar = new JMenuBar();
//set menu bar to the applet
setJMenuBar(regMenuBar);
//add menu "operation" to menu bar
JMenu optionsMenu = new JMenu("Options");
optionsMenu.setMnemonic('O');
regMenuBar.add(optionsMenu);
//add menu "help"
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic('H');
helpMenu.add(jmiAbout = new JMenuItem("About", 'A'));
regMenuBar.add(helpMenu);
//add menu items with mnemonics to menu "options"
optionsMenu.add(jmiSubmit = new JMenuItem("Submit", 'S'));
optionsMenu.add(jmiClear = new JMenuItem("Clear", 'C'));
optionsMenu.add(jmiBack = new JMenuItem("Back", 'B'));
optionsMenu.addSeparator();
optionsMenu.add(jmiExit = new JMenuItem("Exit", 'E'));
//panel p1 to holds text fields
JPanel p1 = new JPanel(new GridLayout(11, 11));
p1.add(new JLabel("First Name: "));
p1.add(jtfFname = new JTextField(15));
p1.add(new JLabel("Last Name: "));
p1.add(jtfLname = new JTextField(15));
p1.add(new JLabel("Street Address 1: "));
p1.add(jtfAddress1 = new JTextField(15));
p1.add(new JLabel("E-mail Address: "));
p1.add(jtfEmail = new JTextField(15));
p1.add(new JLabel("Username: "));
p1.add(jtfUsername = new JTextField(15));
p1.add(new JLabel("Password: "));
p1.add(jtfPassword = new JPasswordField(15));
p1.add(new JLabel("jtfdtype: "));
p1.add(jtfdtype = new JTextField(15));
//panel p2 to holds buttons
JPanel p2 = new JPanel(new FlowLayout());
p2.add(exitButton = new JButton("Exit"));
p2.add(backButton = new JButton("Back"));
p2.add(clearButton = new JButton("Clear"));
p2.add(submitButton = new JButton("Submit"));
//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);
//listners for exit menuitem and button
jmiExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
exitButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
//listner for about menuitem
jmiAbout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
JOptionPane.showMessageDialog(null,
"This is the registration panel"
+ "\n Assignment for University",
"About", JOptionPane.INFORMATION_MESSAGE);
}
});
//listners for clear menuitem and button
jmiClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jtfFname.setText("");
jtfLname.setText("");
jtfAddress1.setText("");
jtfEmail.setText("");
jtfUsername.setText("");
jtfPassword.setText("");
}
});
clearButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
jtfFname.setText("");
jtfLname.setText("");
jtfAddress1.setText("");
jtfEmail.setText("");
jtfUsername.setText("");
jtfPassword.setText("");
}
});
//action listeners for back buttons and redister menuitem
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);
registerInterface.this.dispose();
registerInterface.this.setVisible(false);
}
});
jmiBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Welcome welcome = new Welcome();
welcome.setVisible(true);
welcome.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
registerInterface.this.dispose();
registerInterface.this.setVisible(false);
}
});
//action listeners for Login in button and menu item
submitButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
String a = jtfFname.getText();
String b = jtfLname.getText();
String c = jtfEmail.getText();
String d = jtfAddress1.getText();
String u = jtfUsername.getText();
String f = jtfPassword.getText();
String g = jtfdtype.getText();
Create();
}
});
}
}
and this is the table im using
CREATE TABLE PERSON (
ID SMALLINT UNSIGNED NOT NULL AUTO_INCREMENT,
firstName VARCHAR (50) NOT NULL,
lastName VARCHAR (50) NOT NULL,
email VARCHAR (50) NOT NULL,
address VARCHAR (50),
city VARCHAR (20),
userName VARCHAR (20) NOT NULL,
password VARCHAR (20) NOT NULL,
dtype VARCHAR (20) NOT NULL,
PRIMARY KEY (ID),
UNIQUE KEY (email)
);
You have to use this method PreparedStatement#executeUpdate() instead of executeQuery
Executes the SQL statement in this PreparedStatement object, which
must be an SQL Data Manipulation Language (DML) statement, such as
INSERT, UPDATE or DELETE; or an SQL statement that returns nothing,
such as a DDL statement.
I faced same issue when i tried to delete the record from below code
#Repository
#Transactional
public interface IAeqplUserStagePermissionRepository extends JpaRepository<AeqplUserStagePermissionEntity, Long> {
#Query(value = "DELETE FROM aeqpl_user_stage_permissions WHERE aeqpluser_id = :aeqpluserId",nativeQuery = true)
int deleteByUserId(Long aeqpluserId);
}
Solution: Use #Modifying
#Modifying
#Query(value = "DELETE FROM aeqpl_user_stage_permissions WHERE aeqpluser_id = :aeqpluserId",nativeQuery = true)
int deleteByUserId(#Param("aeqpluserId")Long aeqpluserId);

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) {
}

Making authorization JFrame with MS Access base

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

Categories