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);
Related
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.
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);
}
}
Here is my MS SQL DB
Here is my Java Connection
I have used SQL Server Authentication Login: sa Password: root
Database is loaded, but I can not pass login. Probably can not read a table but I don't know why.
Here is my Login Class
JLabel lbUsername = new JLabel("Username: ");
JLabel lbPassword = new JLabel("Password: ");
JTextField tfUsername = new JTextField(20);
JPasswordField tfPassword = new JPasswordField(20);
JButton btnLogin = new JButton("Uloguj se");
String loginQuery = "SELECT USERNAME, PASSWORD FROM RADNIK";
boolean ulogovan;
public Login() {
setLayout(new MigLayout("fill"));
setTitle("Logovanje");
setSize(250, 150);
setLocationRelativeTo(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
JPanel login = new JPanel(new MigLayout("insets 10"));
login.add(lbUsername);
login.add(tfUsername, "wrap");
login.add(lbPassword);
login.add(tfPassword, "wrap");
add(login, "dock north, grow");
JPanel button = new JPanel(new MigLayout("insets 10"));
button.add(btnLogin, "align center");
btnLogin.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent e) {
if (!tfUsername.getText().equals("")
&& !tfPassword.getPassword().equals("")) {
String username = tfUsername.getText();
String password = "";
for (char ch : tfPassword.getPassword()) {
password += ch;
}
try {
ulogovan = logIn(loginQuery, username, password);
if (ulogovan == true) {
MainFrame main = new MainFrame();
main.setVisible(true);
} else {
JOptionPane
.showMessageDialog(
null,
"Uneli ste neispravno korisnicko ime ili lozinku!",
"Obavestenje",
JOptionPane.WARNING_MESSAGE);
}
} catch (SQLException e1) {
e1.printStackTrace();
}
} else {
JOptionPane.showMessageDialog(null,
"Molimo vas popunite sve podatke!", "Obavestenje",
JOptionPane.INFORMATION_MESSAGE);
}
}
});
add(button, "dock south, grow");
}
public boolean logIn(String sql, String username, String password)
throws SQLException {
ArrayList<String> radnici = new ArrayList<String>();
Statement stmt = DBConnection.getConnection().createStatement();
ResultSet rset = stmt.executeQuery(sql);
while (rset.next()) {
String usernameTemp = rset.getString("USERNAME");
String passwordTemp = rset.getString("PASSWORD");
radnici.add(usernameTemp);
radnici.add(passwordTemp);
}
if (radnici.contains(username) && radnici.contains(password)) {
return true;
}
return false;
}
Any suggestion?
I have two classes, a GUI and a Customer class. The GUI builds the frame and button, and the Customer class gets the info from a database server. I have the ActionPerformed in the Customer class, but it doesn't appear to be noticing when I click the button. Any help is extremely appreciated!
GUI Class:
class GUI {
private static JFrame frame;
public static JTextField textField;
public static JButton btnGetInfo = new JButton("Get Info");
public static JTextArea textArea = new JTextArea();
public static void main (String args [])
throws SQLException {
DriverManager.registerDriver (new oracle.jdbc.driver.OracleDriver());
GUI window = new GUI();
frame = new JFrame();
frame.setBounds(100, 100, 630, 470);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
textArea.setEditable(false);
textArea.setLineWrap(true);
textArea.setBounds(10, 179, 594, 241);
frame.getContentPane().add(textArea);
textField = new JTextField();
textField.setBounds(255, 69, 86, 20);
frame.getContentPane().add(textField);
textField.setColumns(10);
JButton btnClearScreen = new JButton("Clear Screen");
btnClearScreen.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textArea.setText("");
}
});
btnClearScreen.setBounds(492, 11, 112, 23);
frame.getContentPane().add(btnClearScreen);
JLabel lblEnterCustomerId = new JLabel("Enter Customer ID (1-6)");
lblEnterCustomerId.setBounds(240, 43, 153, 14);
frame.getContentPane().add(lblEnterCustomerId);
btnGetInfo.setBounds(255, 115, 89, 23);
frame.getContentPane().add(btnGetInfo);
window.frame.setVisible(true);
}
}
Customer Class:
public class Customer implements ActionListener {
public static void getInfoButton() {
GUI.btnGetInfo.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
System.out.println("TEST");
String getCustID = GUI.textField.getText();
String query = ("select * from customers where CUSTID =" + getCustID);
final String user, pass;
user = "asdf";
pass = "asdf";
try{
Connection conn = DriverManager.getConnection
("jdbc:oracle:thin:#asdf",user,pass);
Statement stmt = conn.createStatement ();
ResultSet rset = stmt.executeQuery (query);
while (rset.next ())
{
GUI.textArea.append((rset.getString("CUSTID") + " - " + rset.getString("CUSTSSN")
+ " - " + rset.getString("LNAME") + " - " + rset.getString("FNAME") + " - " +
rset.getString("STREET") + " - " + rset.getString("CITY") + " - " + rset.getString("STATE") +
" - " + rset.getString("ZIP") + " - " + rset.getString("PHONE") + System.getProperty("line.separator")
+ System.getProperty("line.separator")));
}
}
catch (SQLException e)
{
System.out.println ("Could not load the db"+e);
}
}});
}
#Override
public void actionPerformed(ActionEvent e) {
// TODO Auto-generated method stub
}
}
public static JButton btnGetInfo = new JButton("Get Info");
You should add the actionlistener to this
btnGetInfo.addActionListener(new Customer());
Your Customer should just look like this
public class Customer implements ActionListener {
// delete the uneccessary
#Override
public void actionPerformed(ActionEvent arg0) {
...
}
}
Unnecessary code
public static void getInfoButton() {
GUI.btnGetInfo.addActionListener(new ActionListener() {
I've set up a Gui and a JBDC. I have listed in my tables a username : admin and password : admin and when I input these into the gui login it is still locking me out and im unsure why its locking me out... Below is my code
public class Login extends JFrame {
private JTextField jtfUsername, jtfPassword;
private JButton backButton, loginButton;
private JMenuItem jmiLogin, jmiBack, jmiHelp, jmiAbout;
Login() {
//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);
Login.this.dispose();
Login.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);
Login.this.dispose();
Login.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 {
boolean loggedIn = usernamecheck.checkLogin(jtfUsername.getText(), jtfPassword.getText());
if (!loggedIn) {
JOptionPane.showMessageDialog(null,"Sorry, wrong credentials");
//displayErrorMessage("Sorry, wrong credentials");
return;
}
}
catch (SQLException se) {
se.printStackTrace();
JOptionPane.showMessageDialog(null,
"Sorry, couldn't check your credentials. Check the logs and report the problem to an administrator.");
return;
}
MainMenu mainmenu = new MainMenu();
mainmenu.setVisible(true);
mainmenu.setSize(500, 500);
mainmenu.setLocationRelativeTo(null);
registerInterface regFace = new registerInterface();
regFace.setVisible(false);
Login.this.dispose();
Login.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);
Login.this.dispose();
Login.this.setVisible(false);
}
});
}
public static void main(String arg[]) {
Login frame = new Login();
frame.setSize(500, 500);
frame.setLocationRelativeTo(null);
frame.setVisible(true);
}
}
class usernamecheck {
static final String DATABASE_URL = "jdbc:mysql://localhost:3306/database";
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("Running Check Login \n");
Connection connection = null; // manages connection
PreparedStatement pt = null; // manages prepared statement
Statement stmt = null;
String query="select userName from person where userName = ? and password = ?";
// 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 from person where userName = ? and password = ?");
// process query results
pt.setString(1, username);
ResultSet rs = pt.executeQuery(query);
String orgUname = "", orPass = "";
if (rs.next()) {
orgUname = rs.getString("userName");
orPass = rs.getString("password");
} //end while
if (rs.next() && password.equals(rs.getString("password")) && username.equals(rs.getString("userName"))) {
//do something
return true;
} else {
//do something
return false;
}
}//end try
catch (Exception e) {
} //end catch
return false;
} //end main
}
In your checkLogin(String username, String password) method,
you set username for PreparedStatement as parameter but you forgot to set password
// query database
pt = con.prepareStatement("select userName from person where userName = ? and password = ?");
// process query results
pt.setString(1, username);
??