error : "java.sql.SQLException: No value specified for parameter 1 " - java

public class VerEstoque extends JFrame {
Connection conexao;
PreparedStatement pst;
ResultSet rs;
public void Adicionar()
{
String sql = "INSERT INTO Produtos (Nome, Marca, Loja, Estoque ,ValordeVenda) VALUES (?,?,?,?,?)";
try
{
pst = conexao.prepareStatement(sql);
pst.setString(1,textNome.getText());
pst.setString(2,textMarca.getText());
pst.setString(3,textLoja.getText());
pst.setString(4,textEstoque.getText());
pst.setString(5,textValordeVenda.getText());
pst.execute();
JOptionPane.showMessageDialog(null,"Produto adicionado com sucesso!", "Cadastrado com Sucesso", JOptionPane.INFORMATION_MESSAGE);
listarProdutos();
}
catch(SQLException error)
{
JOptionPane.showMessageDialog(null,"Erro ao adicionar o produto!");
}
}
public void listarProdutos(){
String sql = "Select *from Produtos";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
tblProdutos.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
public void buscarProdutos(){
String sql = "Select *from Produtos where Nome like ?";
try{
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1,textBusca.getText()+"%");
tblProdutos.setModel(DbUtils.resultSetToTableModel(rs));
}
catch(SQLException error){
JOptionPane.showMessageDialog(null, error);
}
}
private JPanel contentPane;
private JTextField textNome;
private JTextField textMarca;
private JTextField textLoja;
private JTextField textEstoque;
private JTextField textValordeVenda;
protected AbstractButton rdbtnRemover;
private JTable tblProdutos;
private JTextField textBusca;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
VerEstoque frame = new VerEstoque();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public VerEstoque() throws ClassNotFoundException {
conexao = BancoDeDados.bancodedados();
setBackground(new Color(238, 238, 238));
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 697, 514);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
textNome = new JTextField();
textNome.setHorizontalAlignment(SwingConstants.CENTER);
textNome.setBounds(289, 68, 134, 28);
contentPane.add(textNome);
textNome.setColumns(10);
textMarca = new JTextField();
textMarca.setHorizontalAlignment(SwingConstants.CENTER);
textMarca.setBounds(289, 96, 134, 28);
contentPane.add(textMarca);
textMarca.setColumns(10);
textLoja = new JTextField();
textLoja.setHorizontalAlignment(SwingConstants.CENTER);
textLoja.setBounds(289, 125, 134, 28);
contentPane.add(textLoja);
textLoja.setColumns(10);
textEstoque = new JTextField();
textEstoque.setHorizontalAlignment(SwingConstants.CENTER);
textEstoque.setBounds(289, 152, 134, 28);
contentPane.add(textEstoque);
textEstoque.setColumns(10);
textValordeVenda = new JTextField();
textValordeVenda.setHorizontalAlignment(SwingConstants.CENTER);
textValordeVenda.setBounds(289, 181, 134, 28);
contentPane.add(textValordeVenda);
textValordeVenda.setColumns(10);
JButton btnAdicionar = new JButton("Adicionar!");
btnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Adicionar();
}
});
btnAdicionar.setBounds(507, 69, 117, 29);
contentPane.add(btnAdicionar);
JButton btnTabela = new JButton("Ver tabela completa de estoque!");
btnTabela.setToolTipText("");
btnTabela.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
listarProdutos();
}
});
btnTabela.setBounds(140, 421, 441, 45);
contentPane.add(btnTabela);
JButton btnBuscar = new JButton("Buscar!");
btnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
buscarProdutos();
}
});
btnBuscar.setBounds(16, 126, 117, 29);
contentPane.add(btnBuscar);
JTextPane txtpnSelecioneAOpo = new JTextPane();
txtpnSelecioneAOpo.setFont(new Font("Comic Sans MS", Font.BOLD | Font.ITALIC, 15));
txtpnSelecioneAOpo.setBackground(SystemColor.window);
txtpnSelecioneAOpo.setText("Selecione a opção que deseja fazer :");
txtpnSelecioneAOpo.setBounds(186, 6, 284, 23);
contentPane.add(txtpnSelecioneAOpo);
JLabel lblNome = new JLabel("Nome :");
lblNome.setBounds(177, 74, 61, 16);
contentPane.add(lblNome);
JLabel lblMarca = new JLabel("Marca :");
lblMarca.setBounds(177, 102, 61, 16);
contentPane.add(lblMarca);
JLabel lblLoja = new JLabel("Loja :");
lblLoja.setBounds(178, 131, 43, 16);
contentPane.add(lblLoja);
JLabel lblEstoque = new JLabel("Estoque :");
lblEstoque.setBounds(177, 158, 61, 16);
contentPane.add(lblEstoque);
JLabel lblValorDeVenda = new JLabel("Valor de Venda :");
lblValorDeVenda.setBounds(177, 187, 108, 16);
contentPane.add(lblValorDeVenda);
JButton btnRemover = new JButton("Remover!");
btnRemover.setBounds(507, 182, 117, 29);
contentPane.add(btnRemover);
JRadioButton rdbtnBuscar = new JRadioButton("Buscar");
rdbtnBuscar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textEstoque.setEditable(false);
textValordeVenda.setEditable(false);
textLoja.setEditable(false);
textMarca.setEditable(false);
}
});
rdbtnBuscar.setBounds(140, 34, 98, 23);
contentPane.add(rdbtnBuscar);
JRadioButton rdbtnAdicionar = new JRadioButton("Adicionar");
rdbtnAdicionar.addKeyListener(new KeyAdapter() {
#Override
public void keyPressed(KeyEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(true);
textLoja.setEditable(true);
textMarca.setEditable(true);
}
});
rdbtnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(true);
textLoja.setEditable(true);
textMarca.setEditable(true);
}
});
rdbtnAdicionar.setBounds(279, 34, 98, 23);
contentPane.add(rdbtnAdicionar);
JRadioButton rdbtnRemover = new JRadioButton("Remover");
rdbtnAdicionar.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textNome.setEditable(true);
textEstoque.setEditable(true);
textValordeVenda.setEditable(false);
textLoja.setEditable(false);
textMarca.setEditable(false);
}
});
rdbtnRemover.setBounds(440, 34, 141, 23);
contentPane.add(rdbtnRemover);
JButton btnCancelar = new JButton("Cancelar!");
btnCancelar.setBounds(417, 126, 98, 28);
contentPane.add(btnCancelar);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(29, 251, 643, 170);
contentPane.add(scrollPane);
tblProdutos = new JTable();
scrollPane.setViewportView(tblProdutos);
tblProdutos.setToolTipText("");
JLabel pesquisaproduto = new JLabel("Nome do Produto para Busca : ");
pesquisaproduto.setBounds(29, 228, 226, 16);
contentPane.add(pesquisaproduto);
textBusca = new JTextField();
textBusca.addKeyListener(new KeyAdapter() {
#Override
public void keyReleased(KeyEvent e) {
buscarProdutos();
}
});
textBusca.setBounds(244, 222, 214, 28);
contentPane.add(textBusca);
textBusca.setColumns(10);
}
}
When I write some text on textBusca and then select buscarProdutos button to do a search, I receive this error:
java.sql.SQLException: No value specified for parameter 1.

You execute the query before setting the first parameter :
pst = conexao.prepareStatement(sql);
rs = pst.executeQuery();
pst.setString(1,textBusca.getText()+"%");
change to
pst = conexao.prepareStatement(sql);
pst.setString(1,textBusca.getText()+"%");
rs = pst.executeQuery();

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

java GUI how to save into text file

i need to save texts from text boxes to text file but any code i found on or made it didn't work, any idea? like any at all? which code would work. i had to use java gui where my teacher teach us about java, but nothing about GUI so ii cant even make save to text file.
public class FlightsPanel extends JPanel {
private Flight flightSelected = null;
private JTextField textFieldDepartureAirport;
private JTextField textFieldArrivalAirport;
private JTextField textFieldDepartureDate;
private JTextField textFieldArrivalDate;
private JRadioButton rdbtnBoarding;
private JRadioButton rdbtnChecking;
private JRadioButton rdbtnAvailable;
private JRadioButton rdbtnClosed;
private JTextField textFieldCost;
private DefaultListModel<String> populateFlights() {
DefaultListModel<String> list = new DefaultListModel<String>();
ArrayList<Flight> FlightList = MainMenu.getAirlineMgr().getFlightList();
for (int i = 0; i < FlightList.size(); i++) {
list.addElement(FlightList.get(i).getFlightNumber());
}
return list;
}
private void displayFlight(String number) {
flightSelected = MainMenu.getAirlineMgr().getFlightByNumber(number);
textFieldDepartureAirport.setText(flightSelected.getDepartureAirport());
textFieldArrivalAirport.setText(flightSelected.getArrivalAirport());
textFieldDepartureDate.setText(flightSelected.getDepartureDate().toString());
textFieldArrivalDate.setText(flightSelected.getArrivalDate().toString());
textFieldCost.setText(Double.toString(flightSelected.getCost()));
if (flightSelected.getFlightStatus() == Flight.Status.AVAILABLE) {
rdbtnAvailable.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.BOARDING) {
rdbtnBoarding.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CHECKING) {
rdbtnChecking.setSelected(true);
} else {
if (flightSelected.getFlightStatus() == Flight.Status.CLOSED) {
rdbtnClosed.setSelected(true);
}
}
}
}
}
private void saveFlight() {
flightSelected.setDepartureAirport(textFieldDepartureAirport.getText());
flightSelected.setArrivalAirport(textFieldArrivalAirport.getText());
flightSelected.setCost(Double.parseDouble(textFieldCost.getText()));
// flightSelected.setDepartureDate(textFieldDepartureDate.getText());
// flightSelected.setArrivalDate(textFieldArrivalDate.getText());
if (rdbtnAvailable.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.AVAILABLE);
} else {
if (rdbtnBoarding.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.BOARDING);
} else {
if (rdbtnChecking.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.CHECKING);
} else {
if (rdbtnClosed.isSelected()) {
flightSelected.setFlightStatus(Flight.Status.CLOSED);
}
}
}
}
}
public FlightsPanel() {
setBackground(new Color(175, 238, 238));
setLayout(null);
JList list = new JList(populateFlights());
list.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
displayFlight(list.getSelectedValue().toString());
}
});
list.setBorder(new LineBorder(new Color(0, 0, 0), 1, true));
list.setBounds(141, 161, 89, 81);
add(list);
JLabel lblNewLabel = new JLabel("Available flights:");
lblNewLabel.setBounds(141, 136, 121, 14);
add(lblNewLabel);
textFieldDepartureAirport = new JTextField();
textFieldDepartureAirport.setBounds(206, 36, 112, 20);
add(textFieldDepartureAirport);
textFieldDepartureAirport.setColumns(10);
JLabel lblNewLabel_1 = new JLabel("Departure Airport:");
lblNewLabel_1.setBounds(206, 11, 112, 14);
add(lblNewLabel_1);
textFieldArrivalAirport = new JTextField();
textFieldArrivalAirport.setColumns(10);
textFieldArrivalAirport.setBounds(10, 36, 112, 20);
add(textFieldArrivalAirport);
JLabel lblArrivalAirport = new JLabel("Arrival Airport:");
lblArrivalAirport.setBounds(10, 11, 112, 14);
add(lblArrivalAirport);
textFieldDepartureDate = new JTextField();
textFieldDepartureDate.setColumns(10);
textFieldDepartureDate.setBounds(206, 91, 192, 20);
add(textFieldDepartureDate);
JLabel lblDepartureDate = new JLabel("Departure Date:");
lblDepartureDate.setBounds(206, 67, 112, 14);
add(lblDepartureDate);
textFieldArrivalDate = new JTextField();
textFieldArrivalDate.setColumns(10);
textFieldArrivalDate.setBounds(10, 91, 192, 20);
add(textFieldArrivalDate);
JLabel lblArrivalDate = new JLabel("Arrival Date:");
lblArrivalDate.setBounds(10, 66, 112, 14);
add(lblArrivalDate);
rdbtnBoarding = new JRadioButton("BOARDING");
rdbtnBoarding.setBounds(10, 211, 112, 23);
add(rdbtnBoarding);
rdbtnChecking = new JRadioButton("CHECKING");
rdbtnChecking.setBounds(10, 237, 112, 23);
add(rdbtnChecking);
rdbtnAvailable = new JRadioButton("AVAILABLE");
rdbtnAvailable.setBounds(10, 159, 112, 23);
add(rdbtnAvailable);
JLabel lblStatus = new JLabel("Status:");
lblStatus.setBounds(20, 138, 220, 14);
add(lblStatus);
rdbtnClosed = new JRadioButton("CLOSED");
rdbtnClosed.setBounds(10, 185, 112, 23);
add(rdbtnClosed);
ButtonGroup group = new ButtonGroup();
group.add(rdbtnBoarding);
group.add(rdbtnChecking);
group.add(rdbtnAvailable);
group.add(rdbtnClosed);
JButton button = new JButton("Cancel");
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
MainMenu.hideFlights();
}
});
button.setBounds(10, 269, 89, 23);
add(button);
JButton btnConfirm = new JButton("Confirm");
btnConfirm.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
saveFlight();
MainMenu.hideFlights();
}
});
btnConfirm.setBounds(351, 269, 89, 23);
add(btnConfirm);
JLabel lblCost = new JLabel("Cost:");
lblCost.setBounds(341, 11, 112, 14);
add(lblCost);
textFieldCost = new JTextField();
textFieldCost.setColumns(10);
textFieldCost.setBounds(328, 36, 112, 20);
add(textFieldCost);
}
}pic of design
You can use basic file writing from Java. The only difference here from basic file writing is that you need to get the Strings to write from the text attributes of your objects. Here is one example from your code:
import java.io.PrintWriter;
try{
PrintWriter fileWriter = new PrintWriter("myFile.txt", "UTF-8");
fileWriter.println(textFieldDepartureAirport.selectAll());
fileWriter.close();
} catch (IOException e) {
e.printStackTrace();
}
Since your teacher did not include much about the UI items, you are able to look up the JavaDoc info about the object type that is holding the data. For example, your text boxes are declared as JTextField, so you can find more info about this class here:
https://docs.oracle.com/javase/7/docs/api/javax/swing/JTextField.html

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;

Loading data from a sqlite database in Java?

I am new to the world of Java and sqlite database. I was trying out some codes about loading data from a database into a tabular view using java in eclipse. Now, here is the thing, when my data loads from the database, i want to add an extra column which contains a checkbox(unchecked). Can someone suggest me how do i implement it? Please note that when i run the code, it works absolutely fine and shows no error....I am able to see all the records in my table without any error. Just want an unchecked checkbox to be added to each row so that when i click on it, i can do something. Thats my goal..
Here is what i tried so far.. I have two classes namely:-
1. sqliteConnection.java(which is for connection )
2. employeeinfo.java class which is for loading the data from the database into a table and other functionalities.
import java.sql.*;
import javax.swing.*;
public class sqliteConnection {
Connection conn = null;
public static Connection dbConnector()
{
try{
Class.forName("org.sqlite.JDBC");
Connection conn = DriverManager.getConnection("jdbc:sqlite:C:\\Users\\user\\Downloads\\Documents\\MyJavaProjects\\Phone\\Employee.sqlite");
JOptionPane.showMessageDialog(null, "Connection Succesful");
return conn;
}
catch(Exception e)
{
JOptionPane.showMessageDialog(null, e);
return null;
}
}
public sqliteConnection() {
// TODO Auto-generated constructor stub
}
}
employeeinfo.java --
import java.awt.BorderLayout;
public class employeeinfo extends JFrame {
private JPanel contentPane;
private JTable table;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
employeeinfo frame = new employeeinfo();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
Connection connection = null;
private JTextField textField;
private JTextField textField_1;
private JTextField textField_2;
private JTextField textField_3;
public employeeinfo() {
connection = sqliteConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 842, 457);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblJframe = new JLabel("Jframe2");
lblJframe.setBounds(47, 37, 46, 14);
contentPane.add(lblJframe);
JButton btnLoad = new JButton("Load");
btnLoad.addActionListener(new ActionListener() {
PreparedStatement pat;
public void actionPerformed(ActionEvent arg0) {
try {
String query = "select eid,Name,Surname,Age from EmployeeInfo ";
pat = connection.prepareStatement(query);
ResultSet rs = pat.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
}
catch (Exception e)
{
}
}
});
btnLoad.setBounds(104, 33, 89, 23);
contentPane.add(btnLoad);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(429, 48, 370, 232);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblName = new JLabel("EID");
lblName.setBounds(10, 98, 46, 21);
contentPane.add(lblName);
textField = new JTextField();
textField.setBounds(107, 99, 126, 20);
contentPane.add(textField);
textField.setColumns(10);
JLabel lblName_1 = new JLabel("Name");
lblName_1.setBounds(10, 154, 46, 14);
contentPane.add(lblName_1);
textField_1 = new JTextField();
textField_1.setColumns(10);
textField_1.setBounds(107, 151, 126, 20);
contentPane.add(textField_1);
JLabel lblSurname = new JLabel("Surname");
lblSurname.setBounds(10, 204, 46, 14);
contentPane.add(lblSurname);
textField_2 = new JTextField();
textField_2.setColumns(10);
textField_2.setBounds(104, 201, 126, 20);
contentPane.add(textField_2);
JLabel lblAge = new JLabel("Age");
lblAge.setBounds(10, 278, 46, 14);
contentPane.add(lblAge);
textField_3 = new JTextField();
textField_3.setColumns(10);
textField_3.setBounds(104, 275, 126, 20);
contentPane.add(textField_3);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
PreparedStatement pat;
try {
String query = "insert into EmployeeInfo(EID,name,surname,age) values(?,?,?,?)";
pat = connection.prepareStatement(query);
pat.setString(1, textField.getText());
pat.setString(2, textField_1.getText());
pat.setString(3, textField_2.getText());
pat.setString(4, textField_3.getText());
pat.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pat.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
btnSave.setBounds(72, 349, 89, 23);
contentPane.add(btnSave);
JButton btnClear = new JButton("Clear");
btnClear.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
textField.setText("");
textField_1.setText("");
textField_2.setText("");
textField_3.setText("");
}
});
btnClear.setBounds(206, 349, 89, 23);
contentPane.add(btnClear);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="Update EmployeeInfo set EID='"+textField.getText()+"',Name='"+textField_1.getText()+"'"
+",Surname='"+textField_2.getText()+"',Age='"+textField_3.getText()+"'where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Saved successfully");
pst.close();
}
catch(Exception f)
{
f.printStackTrace();
}
}
});
btnUpdate.setBounds(323, 349, 89, 23);
contentPane.add(btnUpdate);
JButton btnDelete = new JButton("Delete");
btnDelete.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try
{
String query="delete from EmployeeInfo where EID='"+textField.getText()+"'";
// JOptionPane.showMessageDialog(null, query);
PreparedStatement pst=connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data deleted successfully");
pst.close();
}
catch(Exception ex)
{
ex.printStackTrace();
}
}
});
btnDelete.setBounds(453, 349, 89, 23);
contentPane.add(btnDelete);
}
}
My suggestion is you first go through this article, it's a very simpler way of loading data from ResultSet to DefaultTableModel. After this you have to make some small changes like, you have to add another column heading to the Vector of columnNames and add a column for check boxes. Then when you process each row from the ResultSet you need to add a Boolean value to the row Vector with a checkbox .

Connecting of Database per each JFrame

I have created this Automated Library. And I need to know how to connect my Database per each JFrame.
This is my main method:
package com.Student.GUI;
public class Student_HomePage extends JFrame {
private JPanel contentPane;
private JTextField searchBox;
private static String results[];
private static Connection conn;
private static String searchText;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
DBConnect db = new DBConnect();
conn = db.openConnection();
Student_HomePage frame = new Student_HomePage();
frame.setVisible(true);
frame.setBounds(400,150,599,489);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the frame.
*/
public Student_HomePage() {
setBackground(Color.WHITE);
setIconImage(Toolkit.getDefaultToolkit().getImage("D:\\ITC302-Core Java\\java_workspace\\Pictures\\lala.png"));
setTitle("LookBook");
setResizable(false);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 599, 489);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnHome = new JButton("Home");
btnHome.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnHome.setEnabled(false);
btnHome.setContentAreaFilled(false);
btnHome.setBorder(null);
btnHome.setBounds(144, 24, 95, 25);
contentPane.add(btnHome);
JButton btnAuthors = new JButton("Authors");
btnAuthors.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnAuthors.setContentAreaFilled(false);
btnAuthors.setBorder(null);
btnAuthors.setBounds(241, 24, 95, 25);
contentPane.add(btnAuthors);
JButton btnBooks = new JButton("Books");
btnBooks.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 16));
btnBooks.setContentAreaFilled(false);
btnBooks.setBorder(null);
btnBooks.setBounds(338, 24, 95, 25);
contentPane.add(btnBooks);
JTextArea textArea = new JTextArea();
textArea.setText("|");
textArea.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea.setEditable(false);
textArea.setBounds(227, 11, 26, 57);
contentPane.add(textArea);
JTextArea textArea_1 = new JTextArea();
textArea_1.setText("|");
textArea_1.setFont(new Font("Monospaced", Font.PLAIN, 35));
textArea_1.setEditable(false);
textArea_1.setBounds(325, 11, 26, 57);
contentPane.add(textArea_1);
searchBox = new JTextField();
searchBox.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
searchText = temp;
}
});
searchBox.setColumns(10);
searchBox.setBounds(37, 210, 148, 25);
contentPane.add(searchBox);
JTextArea textArea_2 = new JTextArea();
textArea_2.setText("Search title of books,\r\nauthors or genre");
textArea_2.setFont(new Font("Plantagenet Cherokee", Font.PLAIN, 14));
textArea_2.setBounds(37, 248, 188, 40);
contentPane.add(textArea_2);
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
btnSearch.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\searchIcon.png"));
btnSearch.setContentAreaFilled(false);
btnSearch.setBorder(null);
btnSearch.setBackground(Color.WHITE);
btnSearch.setBounds(185, 210, 87, 25);
contentPane.add(btnSearch);
JLabel label = new JLabel("");
label.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\download.jpg"));
label.setHorizontalAlignment(SwingConstants.CENTER);
label.setBounds(270, 202, 290, 215);
contentPane.add(label);
JLabel bookIcon = new JLabel("");
bookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\BookIcon.png"));
bookIcon.setBounds(101, 78, 116, 90);
contentPane.add(bookIcon);
JLabel lookBookIcon = new JLabel("");
lookBookIcon.setIcon(new ImageIcon("D:\\ITC302-Core Java\\java_workspace\\Pictures\\image.png"));
lookBookIcon.setBounds(213, 74, 290, 135);
contentPane.add(lookBookIcon);
}
public void btnSearchActionPerformed (ActionEvent e, String searchText) {
DBConnect db = new DBConnect();
results = db.selectMatchedData(searchText, conn);
//if (results.length != 0) {
this.dispose();
Student_SearchList window = new Student_SearchList();
window.setVisible(true);
//}
//else {
//Student_Warning window = new Student_Warning();
//window.setVisible(true);
//}
}
}
And this is where I want to connect my Database:
JButton btnSearch = new JButton("Search");
btnSearch.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
String temp = new String(searchBox.getText());
btnSearchActionPerformed(e, temp);
}
});
This whole code is my Main.java.

Categories

Resources