incorrect value from java being inserted into mysql - java

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

Related

Jcombobox not selecting item

Im trying to insert the Jcombobox value into my sqlite database but whenever I run the program, it only inserts '9' in to my database. Please advise. I am trying to import the integer that the user picks into my sqlite database. For some reason, even with the action listener, the default value, 9, is still being inputed into the table and im not sure why. Here is the full code, not including the connection and the Jtable.
public class create extends JFrame {
private JPanel contentPane;
private JTextField textField;
private JTextField textField_1;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
create frame = new create();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connect = null;
private JTextField textField_2;
String uniqueString = UUID.randomUUID().toString();
private JTextField textField_3;
/**
* Create the frame.
*/
public create() {
connect = connection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBackground(new Color(204, 204, 204));
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblStudentName = new JLabel("Student ID:");
lblStudentName.setBounds(96, 69, 72, 16);
contentPane.add(lblStudentName);
textField = new JTextField();
textField.setBounds(173, 64, 216, 26);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblGrade = new JLabel("Grade:");
lblGrade.setBounds(125, 107, 47, 16);
contentPane.add(lblGrade);
JComboBox comboBox = new JComboBox();
comboBox.addItem(9);
comboBox.addItem(10);
comboBox.addItem(11);
comboBox.addItem(12);
comboBox.setBounds(173, 102, 72, 29);
contentPane.add(comboBox);
comboBox.setSelectedItem(9);
comboBox.addActionListener(comboBox);
int selectedNumber = (int)comboBox.getSelectedItem();
JLabel lblInputBookOver = new JLabel("Teacher:");
lblInputBookOver.setBounds(111, 146, 61, 21);
contentPane.add(lblInputBookOver);
textField_1 = new JTextField();
textField_1.setBounds(173, 143, 216, 26);
contentPane.add(textField_1);
textField_1.setColumns(10);
JButton button = new JButton("<");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
for (int count = 0; count <= 0; count++) {
//dispose();
options sc = new options();
sc.setVisible(true);
}
}
});
button.setBounds(6, 6, 30, 29);
contentPane.add(button);
JLabel lblStudentname = new JLabel("Student Name:");
lblStudentname.setBounds(74, 31, 99, 16);
contentPane.add(lblStudentname);
textField_2 = new JTextField();
textField_2.setBounds(173, 26, 216, 26);
contentPane.add(textField_2);
textField_2.setColumns(10);
JLabel lblEmail = new JLabel("Email:");
lblEmail.setBounds(125, 180, 42, 26);
contentPane.add(lblEmail);
textField_3 = new JTextField();
textField_3.setBounds(173, 180, 216, 26);
contentPane.add(textField_3);
textField_3.setColumns(10);
JButton btnCheckout = new JButton("Checkout");
btnCheckout.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
final String uniqueString = UUID.randomUUID().toString().replace("-", "");
try {
String query = "insert into data ('Name', 'Student ID', 'Teacher', 'Grade', 'Email', 'Ebook') values (?,?,?,?,?,?)";
PreparedStatement pst = connect.prepareStatement(query);
pst.setString(1,textField_2.getText() );
pst.setString(2,textField.getText() );
pst.setString(3,textField_1.getText() );
pst.setInt(4, selectedNumber);
pst.setString(5,textField_3.getText() );
pst.setString(6, uniqueString);
for (int count = 0; count <= 0; count++) {
//dispose();
confirm sc = new confirm();
sc.setVisible(true);
count = 0;
}
pst.execute();
pst.close();
}
catch (Exception w){
w.printStackTrace();
}
}
});
btnCheckout.setBounds(173, 218, 117, 29);
contentPane.add(btnCheckout);
}
}
It inserts 9 to your database because the selected item is always 9, and this because you add it first to your combobox. In order to insert the selected value, you will have to use an ActionListener. Then you can take user's selection and do whatever you want.
An example of its usage:
import java.awt.FlowLayout;
import java.io.FileNotFoundException;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;
public class ComboBox extends JFrame {
public ComboBox() {
setDefaultCloseOperation(EXIT_ON_CLOSE);
setSize(300, 300);
setLocationRelativeTo(null);
getContentPane().setLayout(new FlowLayout());
Integer[] numbers = { 4, 5, 8, 123, 42, 634 };
JComboBox<Integer> comboBox = new JComboBox<>(numbers);
comboBox.setSelectedItem(42); // The initial selection is 42.
comboBox.addActionListener(e -> {
int selectedNumber = (int) comboBox.getSelectedItem();
System.out.println("Selected number: " + selectedNumber);
// Do whatever with selected number
});
add(comboBox);
}
public static void main(String[] args) throws FileNotFoundException {
SwingUtilities.invokeLater(() -> new ComboBox().setVisible(true));
}
}

How do I input data from java GUI into MS Access using UCanAccess

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

How to update row selected by id column?

This a 'form'with textfields where admin can update
//For Update
public AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) {
super(mf);
System.out.println("**** admin create qns panel *"+ q.getQuestionNo());
System.out.println("**** admin create qns panel *"+ q.getQuestionDesc());
System.out.println("**** admin create qns panel *"+ q.getOption1());
System.out.println("**** admin create qns panel *"+ q.getOption2());
JLabel lblSet = new JLabel("Set 1");
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSet.setBounds(29, 160, 141, 28) ;
add(lblSet);
JLabel lblQnsDesc = new JLabel("Question Description :");
lblQnsDesc.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsDesc.setBounds(76, 270, 181, 20);
add(lblQnsDesc);
txtfQnsDesc = new JTextField();
txtfQnsDesc.setColumns(10);
txtfQnsDesc.setBounds(76, 306, 639, 26);
add(txtfQnsDesc);
txtfQnsDesc.setText(q.getQuestionDesc());
JLabel lblOp1 = new JLabel("Option 1 :");
lblOp1.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp1.setBounds(76, 365, 103, 20);
add(lblOp1);
txtfOp1 = new JTextField();
txtfOp1.setColumns(10);
txtfOp1.setBounds(218, 362, 146, 26);
add(txtfOp1);
txtfOp1.setText(q.getOption1());
JLabel lblOp2 = new JLabel("Option 2 :");
lblOp2.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp2.setBounds(76, 418, 103, 20);
add(lblOp2);
txtfOp2 = new JTextField();
txtfOp2.setColumns(10);
txtfOp2.setBounds(218, 415, 146, 26);
add(txtfOp2);
txtfOp2.setText(q.getOption2());
JLabel lblOp3 = new JLabel("Option 3 :");
lblOp3.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp3.setBounds(76, 468, 103, 20);
add(lblOp3);
txtfOp3 = new JTextField();
txtfOp3.setColumns(10);
txtfOp3.setBounds(218, 465, 146, 26);
add(txtfOp3);
txtfOp3.setText(q.getOption3());
JLabel lblOp4 = new JLabel("Option 4 :");
lblOp4.setFont(new Font("Tahoma", Font.BOLD, 16));
lblOp4.setBounds(76, 515, 103, 20);
add(lblOp4);
txtfOp4 = new JTextField();
txtfOp4.setColumns(10);
txtfOp4.setBounds(218, 512, 146, 26);
add(txtfOp4);
txtfOp4.setText(q.getOption4());
JLabel lblCorrAns = new JLabel("Correct Answer :");
lblCorrAns.setFont(new Font("Tahoma", Font.BOLD, 16));
lblCorrAns.setBounds(76, 581, 151, 20);
add(lblCorrAns);
txtfCorrAns = new JTextField();
txtfCorrAns.setColumns(10);
txtfCorrAns.setBounds(218, 578, 146, 26);
add(txtfCorrAns);
txtfCorrAns.setText(q.getCorrectAnswer());
JButton button = new JButton("Add");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedAdd();
//actionPerformedOk();
}
});
button.setFont(new Font("Tahoma", Font.BOLD, 16));
button.setBounds(428, 622, 115, 29);
add(button);
JButton btnCancel = new JButton("Cancel");
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnCancel.setFont(new Font("Tahoma", Font.BOLD, 16));
btnCancel.setBounds(712, 622, 115, 29);
add(btnCancel);
JLabel lblQnsNo = new JLabel("Question No. : ");
lblQnsNo.setFont(new Font("Tahoma", Font.BOLD, 16));
lblQnsNo.setBounds(76, 234, 151, 20);
add(lblQnsNo);
txtfQnsNo = new JTextField();
txtfQnsNo.setBounds(218, 228, 146, 26);
add(txtfQnsNo);
txtfQnsNo.setColumns(10);
txtfQnsNo.setText(new Integer(q.getQuestionNo()).toString());
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
} });
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(572, 622, 115, 29);
add(btnUpdate);
}
//Create
private void actionPerformedAdd() {
// retrieve the user input from the text box/area provided
if (validateInput()) {
//amtSpend = Double.parseDouble(txtAmount.getText());
// create an object of expenses based on the input values
//Debugging? -> System.out.println(topic);
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(Integer.parseInt(txtfQnsNo.getText()), txtfQnsDesc.getText(), txtfOp1.getText(),
txtfOp2.getText(), txtfOp3.getText(), txtfOp4.getText(), txtfCorrAns.getText(), topic, set);
// insert to database and check return value
if (QuizDetailsDA.createQuizDetails(e1)) { //Call Create method from QuizDetailsDA
System.out.print("Ok");
JOptionPane.showMessageDialog(myFrame,
"Record created successfully", "Alert",
JOptionPane.INFORMATION_MESSAGE);
// reset text field for next record.
txtfQnsNo.setText("");
txtfQnsDesc.setText("");
txtfOp1.setText("");
txtfOp2.setText("");
txtfOp3.setText("");
txtfOp4.setText("");
txtfCorrAns.setText("");
JPanel contentPane = new AdminQuizOverallPanel(myFrame, set,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
} else
{
System.out.print("Error");
JOptionPane.showMessageDialog(myFrame,
"Database Error. Record not created.", "Alert",
JOptionPane.ERROR_MESSAGE);
}
}
}
private boolean validateInput() {
boolean result = false;
String msg = "";
result = true;
/*int msgType = JOptionPane.ERROR_MESSAGE;
// retrieve the user input from the text box/area provided
String dateSpend = txtDate.getText();
String cat = txtCategory.getText();
String amt = txtAmount.getText();
String cont = txtContent.getText();
if (dateSpend.length() != 10)
msg += "Please enter date in DD-MM-YYYY format.\n";
if (cat.length() == 0)
msg += "Please enter category.\n";
try {
Double.parseDouble(amt); // convert to double for amount
} catch (NumberFormatException e) {
msg += "Plese enter amount in decimal numbers.\n";
}
if (cont.length() == 0)
msg += "Please enter content.\n";
if (msg.length() == 0)
result = true;
else
JOptionPane.showMessageDialog(myFrame, msg, "Alert", msgType);
*/
return result;
}
//Update
public AdminCreateQnsPanel(JFrame mf,String action, QuizDetails e1){
this(mf, action);
txtfQnsNo.setText(new Integer(e1.getQuestionNo()).toString());
txtfQnsDesc.setText(e1.getQuestionDesc());
txtfOp1.setText(e1.getOption1());
txtfOp2.setText(e1.getOption2());
txtfOp3.setText(e1.getOption3());
txtfOp4.setText(e1.getOption4());
txtfCorrAns.setText(e1.getCorrectAnswer());
quizdetails = e1;
}
public AdminCreateQnsPanel(JFrame mf, String action) {
super(mf);
}
public void actionPerformedUpdate(){
int qnsNo = Integer.parseInt(txtfQnsNo.getText());
String qnsDesc = txtfQnsDesc.getText();
String op1 = txtfOp1.getText();
String op2 = txtfOp2.getText();
String op3 = txtfOp3.getText();
String op4 = txtfOp4.getText();
String corrAns = txtfCorrAns.getText();
//***Refer to QuizDetails Entity Class for its constructor
QuizDetails e1 = new QuizDetails(id1,qnsNo, qnsDesc, op1, op2, op3, op4, corrAns);
//Testing -> System.out.println("action performed update " + e1.getQuestionNo());
if(QuizDetailsDA.updateQuizDetails(e1)){ //Call Update method from QuizDetailsDA
JOptionPane.showMessageDialog(myFrame, "Record updated successfully", "Alert", JOptionPane.INFORMATION_MESSAGE);
txtfQnsNo.setEditable(false);
txtfQnsDesc.setEditable(false);
txtfOp1.setEditable(false);
txtfOp2.setEditable(false);
txtfOp3.setEditable(false);
txtfOp4.setEditable(false);
txtfCorrAns.setEditable(false);
}
else{
JOptionPane.showMessageDialog(myFrame, "Database Error. Record not updated.", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
This is the class where JTable is shown.
package studyHelperApp.ui;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import model.QuizDetailsTableModel;
import studyHelperApp.dataAccess.QuizDetailsDA;
import studyHelperApp.entity.QuizDetails;
import javax.swing.JButton;
import javax.swing.JFrame;
import studyHelpersApp.ui.MasterPanel;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.awt.event.ActionEvent;
import javax.swing.JTextField;
import javax.swing.table.DefaultTableModel;
import java.awt.event.KeyAdapter;
import java.awt.event.KeyEvent;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.swing.ListSelectionModel;
import java.awt.Color;
public class AdminQuizOverallPanel extends MasterPanel {
private JTextField txtfSearch;
private JTable table;
private int set;
private String topic;
public static int id1;
private int id;
private void setTableModelFromDB(){
ArrayList <QuizDetails> result = QuizDetailsDA.retrieveAllQuizDetails(set,topic); //Call method from QuizDetailsDA
QuizDetailsTableModel model = new QuizDetailsTableModel(result);
table.setModel(model);
}
public void loadDataTable(){
setTableModelFromDB();
}
/**
* Create the panel.
* #wbp.parser.constructor
*/
public AdminQuizOverallPanel(JFrame mf) {
super(mf);
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set ");
lblSet.setBounds(49, 189, 58, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(637, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(372, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(135, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
JLabel lblSetNo = new JLabel("");
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
lblSetNo.setBounds(107, 189, 31, 31);
add(lblSetNo);
}
public AdminQuizOverallPanel(JFrame mf, int set, String topic) {
super(mf);
this.set = set;
this.topic = topic;
initComponents();
setBounds(100, 100, 900, 750);
setLayout(null);
JLabel lblDisplay = new JLabel("");
lblDisplay.setFont(new Font("Tahoma", Font.PLAIN, 17));
lblDisplay.setBounds(550, 200, 287, 20);
add(lblDisplay);
JLabel lblSet = new JLabel("Set");
lblSet.setBounds(49, 189, 93, 31);
lblSet.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSet);
JLabel lblSetNo = new JLabel(Integer.toString(set));
lblSetNo.setBounds(107, 189, 31, 31);
lblSetNo.setFont(new Font("Tahoma", Font.BOLD, 30));
add(lblSetNo);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(15, 246, 847, 225);
add(scrollPane);
table = new JTable();
loadDataTable();
scrollPane.setViewportView(table);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedDelete();
}
});
btnDelete.setFont(new Font("Tahoma", Font.BOLD, 16));
btnDelete.setBounds(611, 502, 115, 29);
add(btnDelete);
JButton btnSearch = new JButton("Search");
btnSearch.setFont(new Font("Tahoma", Font.BOLD, 16));
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0){
lblDisplay.setText("You searched for: "+txtfSearch.getText());
//findQuizDetails();
}
});
btnSearch.setBounds(744, 160, 93, 29);
add(btnSearch);
txtfSearch = new JTextField();
txtfSearch.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
if(e.getKeyCode()== KeyEvent.VK_ENTER)
lblDisplay.setText("You searched for: "+txtfSearch.getText());
}
});
txtfSearch.setBounds(550, 161, 194, 26);
add(txtfSearch);
txtfSearch.setColumns(10);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
actionPerformedUpdate();
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 16));
btnUpdate.setBounds(365, 502, 115, 29);
add(btnUpdate);
JButton btnAdd = new JButton("Add");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminCreateQnsPanel(myFrame, set ,topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 16));
btnAdd.setBounds(123, 502, 115, 29);
add(btnAdd);
JButton btnBack = new JButton("<Back");
btnBack.setFont(new Font("Tahoma", Font.BOLD, 16));
btnBack.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
JPanel contentPane = new AdminQuizSetNoPanel(myFrame, topic);
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
});
btnBack.setBounds(70, 555, 115, 29);
add(btnBack);
JLabel lblQuizID = new JLabel(topic);
lblQuizID.setFont(new Font("Tahoma", Font.BOLD, 30));
lblQuizID.setBounds(156, 189, 147, 31);
add(lblQuizID);
}
private void initComponents() {
// TODO Auto-generated method stub
}
//Delete
public void actionPerformedDelete(){
System.out.println("performed delete 1****");
int rowSelected = table.getSelectedRow();
System.out.println("performed delete 2 *****"+ rowSelected);
if(rowSelected >= 0){
int resp = JOptionPane.showConfirmDialog(myFrame, "Confirm Delete?", "Confirmation", JOptionPane.YES_NO_CANCEL_OPTION);
if(resp == JOptionPane.YES_OPTION){
int selRowDel = (Integer)table.getModel().getValueAt(rowSelected, 0);
QuizDetailsDA.deleteQuizDetails(selRowDel); //Call Delete method from QuizDetailsDA
//QuizDetailsDA.retrieveAllQuizDetails();
setTableModelFromDB();
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
//Update
public void actionPerformedUpdate(){
int rowSelected = table.getSelectedRow();
if(rowSelected >= 0){
int id = (Integer)table.getModel().getValueAt(rowSelected, 0);
id1 = id;
QuizDetails quizdt = QuizDetailsDA.retrieveQuizDetailsById(id);
//Testing -> System.out.println("**** action performed update **: " + quizdt.getQuestionNo());
//Call method from AdminCreateQnsPanel(JFrame mf, QuizDetails q, int set, String topic) constructor
JPanel contentPane = new AdminCreateQnsPanel(myFrame,quizdt, set, topic);
//After adding set and topic to this above constructor, cancel button is working in AdminCreateQnsPanel
myFrame.getContentPane().removeAll();
myFrame.setContentPane(contentPane);
myFrame.setVisible(true);
}
else {
JOptionPane.showMessageDialog(myFrame, "No record selected", "Alert", JOptionPane.ERROR_MESSAGE);
}
}
}
Data access package
//retrieve quiz by id
public static QuizDetails retrieveQuizDetailsById(int id) {
// declare local variables
QuizDetails quizdetails = null;
ResultSet rs = null;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
// step 1 - connect to database
db.getConnection();
// step 2 - declare the SQL statement
dbQuery = "SELECT * FROM QuizDetails WHERE id=?";
pstmt = db.getPreparedStatement(dbQuery);
// step 3 - execute query
try {
pstmt.setInt(1,id);
rs = pstmt.executeQuery();
if (rs.next()) { // first record found
quizdetails = convertToQuizDetails(rs);
}
} catch (Exception e) {
e.printStackTrace();
}
// step 4 - close connection
db.terminate();
return quizdetails;
}
private static QuizDetails convertToQuizDetails(ResultSet rs) throws SQLException {
QuizDetails quizdetails;
int id = rs.getInt("id");
//String quizID = rs.getString("quizID");
//int setNo = rs.getInt("setNo");
int questionNo = rs.getInt("questionNo");
String questionDesc = rs.getString("questionDesc");
String option1 = rs.getString("option1");
String option2 = rs.getString("option2");
String option3 = rs.getString("option3");
String option4 = rs.getString("option4");
String correctAnswer = rs.getString("correctAnswer");
quizdetails = new QuizDetails(id, questionNo, questionDesc, option1, option2, option3, option4, correctAnswer );
return quizdetails;
}
//Update
public static boolean updateQuizDetails(QuizDetails quizdt) {
//declare local variables
boolean success = false;
DBController db = new DBController();
String dbQuery;
PreparedStatement pstmt;
System.out.println("quiz details da ** 1a " + quizdt.getQuestionNo());
System.out.println("quiz details da ** 1b " + quizdt.getQuestionDesc());
//step 1 - establish connection to database
db.getConnection();
//step 2 - declare the SQL statement
//dbQuery = "UPDATE QuizDetails SET quizID = ?, setNo = ?, questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id = ?";
dbQuery = "UPDATE QuizDetails SET questionNo = ?, questionDesc = ?, option1 = ?, option2 = ?, option3 = ?, option4 =?, correctAnswer = ? WHERE id= ?";
pstmt = db.getPreparedStatement(dbQuery);
System.out.println("quiz details da 2 ** " + quizdt.getQuestionNo());
//step 3 - to update record using executeUpdate method
try {
//pstmt.setInt(1, quizdt.getId());
//pstmt.setString(1, quizdt.getQuizID());
//pstmt.setInt(2, quizdt.getSetNo());
pstmt.setInt(1, quizdt.getQuestionNo());
pstmt.setString(2, quizdt.getQuestionDesc());
pstmt.setString(3, quizdt.getOption1());
pstmt.setString(4, quizdt.getOption2());
pstmt.setString(5, quizdt.getOption3());
pstmt.setString(6, quizdt.getOption4());
pstmt.setString(7,quizdt.getCorrectAnswer());
pstmt.setInt(8, quizdt.getId()); //Cannot be hard coded
System.out.println(quizdt.getId());
System.out.println("quiz details da 3 ** " + quizdt.getQuestionNo());
if (pstmt.executeUpdate() == 1)
success = true;
pstmt.close();
} catch (Exception e) {
e.printStackTrace();
}
//step 4 - close connection
db.terminate();
return success;
}
For instance, I would want to update id 1 and it is updated successfully. However, when I want to update id 5 the updated items of id 5 would be then updated to id 1. Anyone encountered this problem while trying to update database?
You should probably provide more information for such question. It is hard to understand what is the context You are making update at. For example if You are using MySQL then You can solve this by fixing the query. Id should be used in where part and not in set part. Something like this should work fine:
UPDATE TABLE `users` SET `name` = 'John' WHERE `id` = 1;

Java SQL JTable, my first project, how can i improve and simplify my code? any suggestions

I am studying java for 4 months and this project is what i came up with, i know i should make more classes and methods for quality but i am still learning. Please help to me if there is any simpler and cleaner ways to achieve the same results as this. thank you.
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.event.ListSelectionEvent;
import javax.swing.table.DefaultTableModel;
import javax.swing.JTable;
import javax.swing.JLabel;
import java.awt.Font;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Vector;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
public class GUI extends JDialog {
private JTextField txtID;
private JTextField txtName;
private JTextField txtDep;
private JTextField txtGender;
private JTextField txtPosition;
private JTextField txtSalary;
private JTable table;
ResultSet rs;
Connection conn;
Statement statement;
public GUI() throws SQLException {
setBounds(100, 100, 671, 448);
getContentPane().setLayout(null);
try {
// Set System L&F
UIManager.setLookAndFeel(
UIManager.getSystemLookAndFeelClassName());
} catch (UnsupportedLookAndFeelException | ClassNotFoundException | InstantiationException | IllegalAccessException ex) {
System.out.println(ex.getMessage());
}
table = new JTable();
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(10, 11, 635, 205);
getContentPane().add(scrollPane);
scrollPane.setViewportView(table);
String dbURl = "jdbc:mysql://localhost:3306/employees";
try {
conn = DriverManager.getConnection(dbURl, "root", "1234");
if (conn != null) {
System.out.println("Connected");
String s1 = "SELECT * FROM employees";
statement = conn.createStatement();
rs = statement.executeQuery(s1);
table.setModel(buildTableModel(rs));
table.setBounds(10, 11, 634, 216);
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
table.getSelectionModel().addListSelectionListener((ListSelectionEvent event) -> {
try {
if (table.getSelectedRow() >= 0) {
Object employee_id = table.getValueAt(table.getSelectedRow(), 0);
Object full_name = table.getValueAt(table.getSelectedRow(), 1);
Object gender = table.getValueAt(table.getSelectedRow(), 2);
Object department = table.getValueAt(table.getSelectedRow(), 3);
Object position = table.getValueAt(table.getSelectedRow(), 4);
Object salary = table.getValueAt(table.getSelectedRow(), 5);
txtID.setText(employee_id.toString());
txtName.setText(full_name.toString());
txtGender.setText(gender.toString());
txtDep.setText(department.toString());
txtPosition.setText(position.toString());
txtSalary.setText(salary.toString());
}
} catch (Exception ex) {
System.out.println(ex.getMessage());
}
});
JPanel buttonPane = new JPanel();
buttonPane.setBounds(0, 376, 655, 33);
FlowLayout fl_buttonPane = new FlowLayout(FlowLayout.LEFT);
fl_buttonPane.setHgap(10);
buttonPane.setLayout(fl_buttonPane);
getContentPane().add(buttonPane);
JButton btnAdd = new JButton("ADD");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql_stmt = "INSERT INTO employees (full_name,gender,department,position,salary)";
sql_stmt += " VALUES ('" + txtName.getText() + "','" + txtGender.getText() + "','" + txtDep.getText()
+ "','" + txtPosition.getText() + "','" + txtSalary.getText() + "')";
try {
statement.executeUpdate(sql_stmt);
rs = statement.executeQuery("select * from employees");
table.setModel(buildTableModel(rs));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
clearInputBoxes();
}
});
buttonPane.add(btnAdd);
JButton btnUpdate = new JButton("UPDATE");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql_stmt3 = "UPDATE employees SET full_name = '" + txtName.getText() + "'";
sql_stmt3 += ",gender = '" + txtGender.getText() + "'";
sql_stmt3 += ",department = '" + txtDep.getText() + "'";
sql_stmt3 += ",position = '" + txtPosition.getText() + "'";
sql_stmt3 += ",salary = '" + txtSalary.getText() + "'";
sql_stmt3 += " WHERE employee_id = '" + txtID.getText() + "'";
try {
statement.executeUpdate(sql_stmt3);
rs = statement.executeQuery("select * from employees");
table.setModel(buildTableModel(rs));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
clearInputBoxes();
}
});
btnUpdate.setActionCommand("OK");
buttonPane.add(btnUpdate);
getRootPane().setDefaultButton(btnUpdate);
JButton btnDel = new JButton("DELETE");
btnDel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String sql_stmt2 = "DELETE FROM employees WHERE employee_id = '" + txtID.getText() + "'";
try {
statement.executeUpdate(sql_stmt2);
rs = statement.executeQuery("select * from employees");
table.setModel(buildTableModel(rs));
} catch (SQLException e) {
System.out.println(e.getMessage());
}
clearInputBoxes();
}
});
btnDel.setActionCommand("Cancel");
buttonPane.add(btnDel);
JLabel lblID = new JLabel("ID");
lblID.setFont(new Font("Verdana", Font.BOLD, 14));
lblID.setBounds(26, 237, 79, 23);
getContentPane().add(lblID);
JLabel lblFullname = new JLabel("Fullname");
lblFullname.setFont(new Font("Verdana", Font.BOLD, 14));
lblFullname.setBounds(26, 271, 79, 23);
getContentPane().add(lblFullname);
JLabel lblGender = new JLabel("Gender");
lblGender.setFont(new Font("Verdana", Font.BOLD, 14));
lblGender.setBounds(340, 237, 79, 23);
getContentPane().add(lblGender);
JLabel lblPosition = new JLabel("Position");
lblPosition.setFont(new Font("Verdana", Font.BOLD, 14));
lblPosition.setBounds(340, 271, 79, 23);
getContentPane().add(lblPosition);
JLabel lblDep = new JLabel("DEP");
lblDep.setFont(new Font("Verdana", Font.BOLD, 14));
lblDep.setBounds(26, 305, 79, 23);
getContentPane().add(lblDep);
JLabel lblSalary = new JLabel("Salary");
lblSalary.setFont(new Font("Verdana", Font.BOLD, 14));
lblSalary.setBounds(340, 305, 79, 23);
getContentPane().add(lblSalary);
txtID = new JTextField();
txtID.setBounds(115, 240, 215, 20);
getContentPane().add(txtID);
txtID.setColumns(10);
txtName = new JTextField();
txtName.setColumns(10);
txtName.setBounds(115, 274, 215, 20);
getContentPane().add(txtName);
txtDep = new JTextField();
txtDep.setColumns(10);
txtDep.setBounds(115, 308, 215, 20);
getContentPane().add(txtDep);
txtGender = new JTextField();
txtGender.setColumns(10);
txtGender.setBounds(429, 240, 107, 20);
getContentPane().add(txtGender);
txtPosition = new JTextField();
txtPosition.setColumns(10);
txtPosition.setBounds(429, 274, 215, 20);
getContentPane().add(txtPosition);
txtSalary = new JTextField();
txtSalary.setColumns(10);
txtSalary.setBounds(429, 308, 215, 20);
getContentPane().add(txtSalary);
}
public static DefaultTableModel buildTableModel(ResultSet rs) throws SQLException {
ResultSetMetaData metaData = rs.getMetaData();
// names of columns
Vector<String> columnNames = new Vector<String>();
int columnCount = metaData.getColumnCount();
for (int column = 1; column <= columnCount; column++) {
columnNames.add(metaData.getColumnName(column));
}
// data of the table
Vector<Vector<Object>> data = new Vector<Vector<Object>>();
while (rs.next()) {
Vector<Object> vector = new Vector<Object>();
for (int columnIndex = 1; columnIndex <= columnCount; columnIndex++) {
vector.add(rs.getObject(columnIndex));
}
data.add(vector);
}
return new DefaultTableModel(data, columnNames);
}
private void clearInputBoxes() {
txtID.setText("");
txtName.setText("");
txtGender.setText("");
txtDep.setText("");
txtPosition.setText("");
txtSalary.setText("");
}
public static void main(String[] args) throws Exception {
GUI g = new GUI();
g.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
g.setVisible(true);
}
}
if there is any simpler and cleaner ways to achieve the same results
Don't use null layouts. Swing was designed to be used with layout managers. Read the section from the Swing tutorial on Layout Managers for more information and working examples.
Use PreparedStatement for your SQL. It is easier to create and maintain the SQL statement. Read the API for basic information about the class and then search the forum/web for examples.

NullPointerException on insert operation

I'm trying to insert into my database through the actionPerformed method for my button.
But i keep getting "java.lang.NullPointerException" The button press is supposed to insert from the textboxes and send it to the database, but i currently get a java null pointer exception in the actionperformed method. Can you help me?
(You can copy paste the code and run it directly if it would help)
(There is a connection to the Database, so it's not that)
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;
import java.awt.BorderLayout;
import javax.swing.JToolBar;
import javax.swing.JDesktopPane;
import javax.swing.BoxLayout;
import javax.swing.JLabel;
import javax.swing.JTextField;
import java.awt.FlowLayout;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JRadioButton;
import java.awt.Font;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.JPasswordField;
import javax.swing.JList;
import javax.swing.JComboBox;
public class MyGuiApplication {
//database globals
private Connection con;
private Statement st;
private ResultSet rs;
//gui globals
private JFrame frame;
private JTextField EmailTextField;
private JTextField FirstNameTextField;
private JTextField LastNameTextField;
private JTextField MobileNumberTextField;
private JLabel lblPassword;
private JLabel lblConfirmPassword;
private JRadioButton MrsMsBTN;
private JRadioButton MrBTN;
private JLabel lblTitle;
private JLabel lblFirstName;
private JLabel lblLastName;
private JLabel lblMobileNumber;
private JLabel lblNewCustomer;
private JLabel lblDeliveryInformation;
private JLabel lblInCaseWe;
private JLabel lblMandatoryField;
private JPasswordField ConfirmPasswordField;
private JPasswordField PasswordField;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
MyGuiApplication window = new MyGuiApplication();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public MyGuiApplication() {
initialize();
DBConnect();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 456, 560);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
//KNAPPEN
JButton btnUpdate = new JButton("update");
//ACTION LISTENER - TILFØJ DATA TIL DATABASEN VED TRYK PÅ KNAP
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0)
{
try
{
String sql="INSERT INTO customers (Email_Address, Password, User_ID, Title_Mr/Mrs, First_Name, Last_Name, Phone_Number, How_did_you_find_us?, Agree_to_terms_&_conditions, Receive_mails_and_offers?) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)";
PreparedStatement preparedStatement=con.prepareStatement(sql);
preparedStatement.setString (1, EmailTextField.getText()); // email addresse
preparedStatement.setString (2, PasswordField.getText()); // Stemme overens med ConfirmPasswordField?
preparedStatement.setInt (3, ((Integer) null)); //user ID primary key auto increment
preparedStatement.setString (4, "Mr"); // Title mrs/mr
preparedStatement.setString (5, FirstNameTextField.getText());
preparedStatement.setString (6, LastNameTextField.getText());
preparedStatement.setString (7, MobileNumberTextField.getText());
preparedStatement.setString (8, null); //dropdown menu, "how did you find us"?
preparedStatement.setBoolean(9, true); // agree to terms
preparedStatement.setBoolean(10, true); // receive email offers from us
preparedStatement.executeUpdate();
} catch (Exception e) {
System.out.print(e);
}
}
});
btnUpdate.setBounds(138, 474, 89, 23);
frame.getContentPane().add(btnUpdate);
EmailTextField = new JTextField();
EmailTextField.setBounds(163, 68, 186, 20);
frame.getContentPane().add(EmailTextField);
EmailTextField.setColumns(10);
FirstNameTextField = new JTextField();
FirstNameTextField.setBounds(163, 241, 186, 20);
frame.getContentPane().add(FirstNameTextField);
FirstNameTextField.setColumns(10);
LastNameTextField = new JTextField();
LastNameTextField.setBounds(163, 286, 186, 20);
frame.getContentPane().add(LastNameTextField);
LastNameTextField.setColumns(10);
MobileNumberTextField = new JTextField();
MobileNumberTextField.setBounds(163, 331, 186, 20);
frame.getContentPane().add(MobileNumberTextField);
MobileNumberTextField.setColumns(10);
JCheckBox TermsConditionsCheckBox = new JCheckBox("Yes, i agree to the Terms and Conditions.*");
TermsConditionsCheckBox.setBounds(115, 418, 266, 23);
frame.getContentPane().add(TermsConditionsCheckBox);
JCheckBox EmailOffersCheckBox = new JCheckBox("Yes, i wish to receiver Email offers from Zalando.");
EmailOffersCheckBox.setBounds(115, 444, 319, 23);
frame.getContentPane().add(EmailOffersCheckBox);
JLabel lblEmailAddress = new JLabel("Email Address*");
lblEmailAddress.setBounds(47, 71, 106, 14);
frame.getContentPane().add(lblEmailAddress);
lblPassword = new JLabel("Password*");
lblPassword.setBounds(65, 112, 88, 14);
frame.getContentPane().add(lblPassword);
lblConfirmPassword = new JLabel("Confirm password*");
lblConfirmPassword.setBounds(25, 143, 128, 14);
frame.getContentPane().add(lblConfirmPassword);
MrsMsBTN = new JRadioButton("Mrs./Ms.");
MrsMsBTN.setSelected(true);
MrsMsBTN.setBounds(138, 211, 76, 23);
frame.getContentPane().add(MrsMsBTN);
MrBTN = new JRadioButton("Mr.");
MrBTN.setBounds(216, 211, 109, 23);
frame.getContentPane().add(MrBTN);
lblTitle = new JLabel("Title*");
lblTitle.setBounds(95, 216, 37, 14);
frame.getContentPane().add(lblTitle);
lblFirstName = new JLabel("First name*");
lblFirstName.setBounds(65, 244, 88, 14);
frame.getContentPane().add(lblFirstName);
lblLastName = new JLabel("Last name*");
lblLastName.setBounds(65, 289, 88, 14);
frame.getContentPane().add(lblLastName);
lblMobileNumber = new JLabel("Mobile Number");
lblMobileNumber.setBounds(47, 334, 106, 14);
frame.getContentPane().add(lblMobileNumber);
lblNewCustomer = new JLabel("New Customer");
lblNewCustomer.setFont(new Font("Tahoma", Font.BOLD, 16));
lblNewCustomer.setBounds(25, 37, 149, 14);
frame.getContentPane().add(lblNewCustomer);
lblDeliveryInformation = new JLabel("Delivery information");
lblDeliveryInformation.setFont(new Font("Tahoma", Font.PLAIN, 12));
lblDeliveryInformation.setBounds(10, 181, 109, 14);
frame.getContentPane().add(lblDeliveryInformation);
lblInCaseWe = new JLabel("In case we need to contact you about your order");
lblInCaseWe.setFont(new Font("Tahoma", Font.PLAIN, 10));
lblInCaseWe.setBounds(163, 362, 251, 14);
frame.getContentPane().add(lblInCaseWe);
lblMandatoryField = new JLabel("* mandatory field");
lblMandatoryField.setFont(new Font("Tahoma", Font.ITALIC, 11));
lblMandatoryField.setBounds(25, 478, 100, 14);
frame.getContentPane().add(lblMandatoryField);
ConfirmPasswordField = new JPasswordField();
ConfirmPasswordField.setBounds(163, 142, 186, 20);
frame.getContentPane().add(ConfirmPasswordField);
PasswordField = new JPasswordField();
PasswordField.setBounds(163, 112, 186, 20);
frame.getContentPane().add(PasswordField);
JComboBox comboBox = new JComboBox();
comboBox.setBounds(163, 391, 186, 20);
//comboBox.add("Facebook.com", comboBox);
frame.getContentPane().add(comboBox);
JLabel lblHowDidYou = new JLabel("How did you find us?*");
//ADD OPTIONS TO WHERE YOU FOUND US
lblHowDidYou.setBounds(25, 394, 128, 14);
frame.getContentPane().add(lblHowDidYou);
}
public void DBConnect(){
try{
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/zalando", "root","");
st = con.createStatement();
}catch(Exception ex){
System.out.println("Error: " +ex);
}
}
}
}
Had you checked the not null fields in the database table.Copy the things in the output window.That's the stack trace.

Categories

Resources