Problem in Deleting Row from JTable And Mysql - java

I Need to delete selected row from Jtable which connected to Mysql database
I successfully make another class to add book and it's work fine
i make this class to delete book added in the table , but i cannot find where the problem in my code , and i don't get any error
IDE : netBeans
here is the class code :
package finallibrary;
import java.awt.*;
import javax.swing.*;
import javax.swing.border.*;
import net.proteanit.sql.DbUtils;
import java.sql.*;
import java.awt.event.*;
import javax.swing.table.DefaultTableModel;
public class BookDetails extends JFrame implements ActionListener {
private JPanel contentPane;
private JTable table;
private JTextField search;
private JButton b1, b2, b3;
public static void main(String[] args) {
new BookDetails().setVisible(true);
}
public void Book() {
try {
Conn con = new Conn();
String sql = "select * from book";
PreparedStatement st = con.c.prepareStatement(sql);
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
st.close();
con.c.close();
} catch (Exception e) {
}
}
public BookDetails() {
setTitle("Book List");
setBounds(350, 200, 890, 475);
contentPane = new JPanel();
contentPane.setBackground(Color.WHITE);
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(36, 133, 802, 268);
contentPane.add(scrollPane);
table = new JTable();
table.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent arg0) {
int row = table.getSelectedRow();
search.setText(table.getModel().getValueAt(row, 1).toString());
}
});
table.setBackground(new Color(240, 248, 255));
table.setForeground(Color.DARK_GRAY);
table.setFont(new Font("Trebuchet MS", Font.BOLD, 16));
scrollPane.setViewportView(table);
JButton b1 = new JButton("Search");
b1.addActionListener(this);
b1.setFont(new Font("Trebuchet MS", Font.BOLD, 18));
b1.setBounds(564, 89, 108, 33);
contentPane.add(b1);
JButton b2 = new JButton("Delete");
b2.addActionListener(this);
b2.setFont(new Font("Trebuchet MS", Font.BOLD, 18));
b2.setBounds(712, 89, 108, 33);
contentPane.add(b2);
JLabel l1 = new JLabel("Book Details");
l1.setForeground(SystemColor.desktop);
l1.setFont(new Font("Bookman Old Style", Font.PLAIN, 30));
l1.setBounds(302, 11, 400, 47);
contentPane.add(l1);
search = new JTextField();
search.setForeground(new Color(47, 79, 79));
search.setFont(new Font("Book Antiqua", Font.PLAIN, 17));
search.setBounds(189, 89, 357, 33);
contentPane.add(search);
search.setColumns(10);
JButton b3 = new JButton("Back");
b3.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
Home home = new Home();
home.setVisible(true);
}
});
b3.addMouseListener(new MouseAdapter() {
#Override
public void mouseClicked(MouseEvent e) {
setVisible(false);
Home home = new Home();
home.setVisible(true);
}
});
b3.setFont(new Font("Trebuchet MS", Font.BOLD, 18));
b3.setBounds(36, 89, 103, 33);
contentPane.add(b3);
JPanel panel = new JPanel();
panel.setBorder(new TitledBorder(new LineBorder(new Color(0, 128, 128), 3, true), "Book-Details",
TitledBorder.LEADING, TitledBorder.TOP, null, new Color(0, 128, 0)));
panel.setBounds(10, 52, 849, 373);
contentPane.add(panel);
panel.setBackground(Color.WHITE);
Book();
}
public void actionPerformed(ActionEvent ae) {
try {
Conn con = new Conn();
if (ae.getSource() == b1) {
String sql = "select * from book where concat(name, book_id) like ?";
PreparedStatement st = con.c.prepareStatement(sql);
st.setString(1, "%" + search.getText() + "%");
ResultSet rs = st.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(rs));
rs.close();
st.close();
}
if (ae.getSource() == b2) {
String sql = "delete from book where name = '" + search.getText() + "'";
PreparedStatement st = con.c.prepareStatement(sql);
JDialog.setDefaultLookAndFeelDecorated(true);
int response = JOptionPane.showConfirmDialog(null, "Do you want to continue?", "Confirm",
JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
if (response == JOptionPane.NO_OPTION) {
} else if (response == JOptionPane.YES_OPTION) {
int rs = st.executeUpdate();
JOptionPane.showMessageDialog(null, "Deleted !!");
} else if (response == JOptionPane.CLOSED_OPTION) {
}
st.close();
}
con.c.close();
} catch (Exception e) {
}
}
}

Related

How to save changes made to an array list in java

I am just a beginner in java coding and I want to know how I can save changes made to an array list through a GUI i have created. This code allows to store data, remove, add, update student information. However it is only temporarily since it is not connected to the hard disk to permanently store this information. I am wondering how I can make this code save the modified information made to it after i close it. I thank you for your time and consideration. The main class code is:
public class StudentDataStorage {
private JFrame frame;
private JTextField textStudentName;
private JTextField textStudentId;
private JTextField textCourseId;
private JTextField textCourseSubject;
void clearFields() {
textStudentName.setText("");
textStudentId.setText("");
textCourseId.setText("");
textCourseSubject.setText("");
}
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
StudentDataStorage window = new StudentDataStorage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
private ArrayList<Student> arrayList;
private ListIterator<Student> listIterator;
int size;
public StudentDataStorage() {
initialize();
arrayList = new ArrayList<>();
size = 0;
arrayList.add(new Student("Jon Rugova", 340007862, "ISTE.121.500", "CompProblemSolvingInfoDomainII"));
arrayList.add(new Student("Sindi Rryta", 125172286, "ACCT.210.501", "Management Accounting"));
arrayList.add(new Student("Arianit Sylafeta", 545919686, "MTSC.231..501", "Contemporary Science: Biology"));
arrayList.add(new Student("Enxo Muçaj", 223375558, "POLS.110.500", "American Politics"));
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 991, 656);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
JPanel panel = new JPanel();
panel.setBounds(6, 0, 979, 65);
frame.getContentPane().add(panel);
panel.setLayout(null);
JLabel lblNewLabel = new JLabel("Student Data Storage");
lblNewLabel.setBounds(287, 6, 393, 44);
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setFont(new Font("Tahoma", Font.BOLD, 36));
panel.add(lblNewLabel);
JPanel panel_1 = new JPanel();
panel_1.setBounds(6, 64, 979, 315);
frame.getContentPane().add(panel_1);
panel_1.setLayout(null);
JLabel lblStudentName = new JLabel("Student Name");
lblStudentName.setFont(new Font("Tahoma", Font.BOLD, 20));
lblStudentName.setBounds(164, 57, 196, 23);
lblStudentName.setHorizontalAlignment(SwingConstants.LEFT);
panel_1.add(lblStudentName);
textStudentName = new JTextField();
textStudentName.setFont(new Font("Tahoma", Font.BOLD, 20));
textStudentName.setBounds(372, 55, 421, 26);
panel_1.add(textStudentName);
textStudentName.setColumns(10);
JLabel lblIdNumber = new JLabel("Student ID");
lblIdNumber.setHorizontalAlignment(SwingConstants.LEFT);
lblIdNumber.setFont(new Font("Tahoma", Font.BOLD, 20));
lblIdNumber.setBounds(164, 101, 196, 23);
panel_1.add(lblIdNumber);
textStudentId = new JTextField();
textStudentId.setFont(new Font("Tahoma", Font.BOLD, 20));
textStudentId.setColumns(10);
textStudentId.setBounds(372, 99, 421, 26);
panel_1.add(textStudentId);
JLabel lblCourseId = new JLabel("Course ID");
lblCourseId.setHorizontalAlignment(SwingConstants.LEFT);
lblCourseId.setFont(new Font("Tahoma", Font.BOLD, 20));
lblCourseId.setBounds(164, 145, 196, 23);
panel_1.add(lblCourseId);
textCourseId = new JTextField();
textCourseId.setFont(new Font("Tahoma", Font.BOLD, 20));
textCourseId.setColumns(10);
textCourseId.setBounds(372, 143, 421, 26);
panel_1.add(textCourseId);
JLabel lblCourseSubject = new JLabel("Course Subject");
lblCourseSubject.setHorizontalAlignment(SwingConstants.LEFT);
lblCourseSubject.setFont(new Font("Tahoma", Font.BOLD, 20));
lblCourseSubject.setBounds(164, 186, 196, 23);
panel_1.add(lblCourseSubject);
textCourseSubject = new JTextField();
textCourseSubject.setFont(new Font("Tahoma", Font.BOLD, 20));
textCourseSubject.setColumns(10);
textCourseSubject.setBounds(372, 184, 421, 26);
panel_1.add(textCourseSubject);
JPanel panel_2 = new JPanel();
panel_2.setBounds(6, 378, 979, 250);
frame.getContentPane().add(panel_2);
panel_2.setLayout(null);
JButton btnFirst = new JButton("First");
btnFirst.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
size = arrayList.size();
listIterator = arrayList.listIterator();
Student ss;
ss = listIterator.next();
textStudentName.setText(ss.getName());
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}
});
btnFirst.setFont(new Font("Tahoma", Font.BOLD, 18));
btnFirst.setBounds(151, 56, 139, 68);
panel_2.add(btnFirst);
JButton btnNext = new JButton("Next");
btnNext.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
if(listIterator.hasNext()) {
Student ss;
ss = listIterator.next();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}else {
JOptionPane.showMessageDialog(null, "You Have Reached the Last Student.");
}
}
}
});
btnNext.setFont(new Font("Tahoma", Font.BOLD, 18));
btnNext.setBounds(317, 56, 139, 68);
panel_2.add(btnNext);
JButton btnAdd = new JButton("Add Data");
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
arrayList.add(new Student(name, studentid, courseid, coursesubject));
size = arrayList.size();
clearFields();
JOptionPane.showMessageDialog(null, "Student Data Added Successfully!");
}
}
});
btnAdd.setFont(new Font("Tahoma", Font.BOLD, 18));
btnAdd.setBounds(483, 56, 139, 68);
panel_2.add(btnAdd);
JButton btnRemove = new JButton("Remove");
btnRemove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
for(Student s:arrayList) {
if(studentid == s.getStudentId()) {
arrayList.remove(s);
listIterator = arrayList.listIterator();
clearFields();
JOptionPane.showMessageDialog(null, "Student Data Removed Successfully!");
break;
}
}
}
}
});
btnRemove.setFont(new Font("Tahoma", Font.BOLD, 18));
btnRemove.setBounds(649, 56, 139, 68);
panel_2.add(btnRemove);
JButton btnLast = new JButton("Last");
btnLast.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
size = arrayList.size();
listIterator = arrayList.listIterator(arrayList.size());
if(listIterator.hasPrevious()) {
Student ss;
ss = listIterator.previous();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}
}
});
btnLast.setFont(new Font("Tahoma", Font.BOLD, 18));
btnLast.setBounds(151, 144, 139, 68);
panel_2.add(btnLast);
JButton btnPrevious = new JButton("Previous");
btnPrevious.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
if(listIterator.hasPrevious()) {
Student ss;
ss = listIterator.previous();
textStudentName.setText(ss.getName());;
textStudentId.setText(""+ss.getStudentId());
textCourseId.setText(ss.getCourseId());
textCourseSubject.setText(ss.getCourseSubject());
}else {
JOptionPane.showMessageDialog(null, "You Have Reached the First Student.");
}
}
}
});
btnPrevious.setFont(new Font("Tahoma", Font.BOLD, 18));
btnPrevious.setBounds(317, 144, 139, 68);
panel_2.add(btnPrevious);
JButton btnUpdate = new JButton("Update Data");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
if(textStudentName.getText().contentEquals("")||textStudentId.getText().contentEquals("")||textCourseId.getText().contentEquals("")||textCourseSubject.getText().contentEquals("")) {
JOptionPane.showMessageDialog(null, "Error: Some Fields Are Empty!");
}else {
String name = textStudentName.getText();
int studentid = Integer.parseInt(textStudentId.getText());
String courseid = textCourseId.getText();
String coursesubject = textCourseSubject.getText();
for(Student s:arrayList) {
if(studentid == s.getStudentId()) {
s.setName(name);
s.setCourseId(courseid);
s.setCourseSubject(coursesubject);
JOptionPane.showMessageDialog(null, "Changes Have Been Made Successfully!");
break;
}
}
}
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 18));
btnUpdate.setBounds(483, 144, 139, 68);
panel_2.add(btnUpdate);
JButton btnExit = new JButton("Exit");
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
System.exit(0);
}
});
btnExit.setFont(new Font("Tahoma", Font.BOLD, 18));
btnExit.setBounds(649, 144, 139, 68);
panel_2.add(btnExit);
}
}
-jon

How to save Data to mysql [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
I ve been working on a phonebook program on eclipse java
but and idk how to save information from a textfield to mysql and then be able use it in search, such as writing the name and finding all the info of the specific contact
I also want to save it to my sql
thats my code:
public class Phone {
private JFrame frame;
private JTextField firstfield;
private JTextField phonefield;
private JTextField emailfield;
private JTextField lastfield;
private JPanel MainScreen;
private JPanel newcontact;
private JPanel searchscreen;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Phone window = new Phone();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public Phone() {
initialize();
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
frame = new JFrame();
frame.setBounds(100, 100, 450, 300);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(new CardLayout(0, 0));
final JPanel MainScreen = new JPanel();
frame.getContentPane().add(MainScreen, "name_6058038854379");
MainScreen.setLayout(null);
MainScreen.setVisible(true);
final JPanel newcontact = new JPanel();
newcontact.setLayout(null);
frame.getContentPane().add(newcontact, "name_791613670731");
newcontact.setVisible(false);
final JPanel searchscreen = new JPanel();
frame.getContentPane().add(searchscreen, "name_6068807854350");
searchscreen.setVisible(false);
JButton newrecord = new JButton("New Record");
newrecord.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
newcontact.setVisible(true);
MainScreen.setVisible(false);
}
});
newrecord.setBounds(63, 99, 116, 52);
MainScreen.add(newrecord);
JButton Search = new JButton("Search");
Search.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
searchscreen.setVisible(true);
newcontact.setVisible(false);
}
});
Search.setBounds(243, 99, 102, 52);
MainScreen.add(Search);
JLabel myphonebook = new JLabel(" My Phonebook");
myphonebook.setBounds(162, 44, 102, 14);
MainScreen.add(myphonebook);
JLabel first = new JLabel("First Name:");
first.setBounds(118, 83, 66, 14);
newcontact.add(first);
JLabel last = new JLabel("Last Name:");
last.setBounds(118, 108, 66, 14);
newcontact.add(last);
JLabel Phone = new JLabel("Phone:");
Phone.setBounds(118, 143, 66, 14);
newcontact.add(Phone);
JLabel Emailadress = new JLabel("Email Adress:");
Emailadress.setBounds(118, 180, 66, 14);
newcontact.add(Emailadress);
firstfield = new JTextField();
firstfield.setColumns(10);
firstfield.setBounds(220, 80, 86, 20);
newcontact.add(firstfield);
lastfield = new JTextField();
lastfield.setColumns(10);
lastfield.setBounds(220, 108, 86, 20);
newcontact.add(lastfield);
phonefield = new JTextField();
phonefield.setColumns(10);
phonefield.setBounds(220, 140, 86, 20);
newcontact.add(phonefield);
emailfield = new JTextField();
emailfield.setColumns(10);
emailfield.setBounds(220, 177, 86, 20);
newcontact.add(emailfield);
JLabel lblNewContact = new JLabel("New Contact");
lblNewContact.setBounds(166, 30, 86, 14);
newcontact.add(lblNewContact);
JButton Save = new JButton("Save");
Save.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
String firstname=firstfield.getText();
String lastname=lastfield.getText();
String phonenumber=phonefield.getText();
String emailadress=emailfield.getText();
}
});
Save.setBounds(81, 232, 89, 23);
newcontact.add(Save);
JButton cancel = new JButton("Cancel");
cancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
newcontact.setVisible(false);
MainScreen.setVisible(true);
}
});
cancel.setBounds(283, 232, 89, 23);
newcontact.add(cancel);
JPanel panel_1 = new JPanel();
frame.getContentPane().add(panel_1, "name_6081212161880");
}
}
Write this into your savecommand. You should only create a database an table and change the uppercased words.
try
{
// create a mysql database connection
String myDriver = "org.gjt.mm.mysql.Driver";
String myUrl = "jdbc:mysql://LOCATION/DATABASE";
Class.forName(myDriver);
Connection conn = DriverManager.getConnection(myUrl, "root", "");
// create a sql date object so we can use it in our INSERT statement
Calendar calendar = Calendar.getInstance();
java.sql.Date startDate = new java.sql.Date(calendar.getTime().getTime());
// the mysql insert statement
String query = " insert into TABLE (first_name, last_name, phone_number, email_adress)"
+ " values (?, ?, ?, ?)";
// create the mysql insert preparedstatement
PreparedStatement preparedStmt = conn.prepareStatement(query);
preparedStmt.setString (1, firstname);
preparedStmt.setString (2, lastname);
preparedStmt.setString (3, phonenumber);
preparedStmt.setString (4, emailadress);
// execute the preparedstatement
preparedStmt.execute();
conn.close();
}
catch (Exception e)
{
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
}

ORA-00927: missing equal sign java eclipse

When I try to run a code I got an error message "ORA-00927: missing equal sign" which can not detect it in the code and can not fix it. I mean that error is in the UPDATE method but i'm not sure.
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.JFrame;
import javax.swing.JPanel;strong text
import javax.swing.border.EmptyBorder;
import net.proteanit.*;
import javax.swing.JLabel;
import java.awt.Font;
import javax.swing.JButton;
import javax.swing.JTable;
import javax.swing.JScrollPane;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import java.sql.*;
import javax.swing.*;
import net.proteanit.sql.DbUtils;
public class Korisnici extends JFrame {
private JPanel contentPane;
private JTable table;
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
Korisnici frame = new Korisnici();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
Connection connection = null;
protected ResultSet rs;
private JTextField textFieldPhoneNumber;
private JTextField textFieldName;
private JTextField textFieldEmail;
private JTextField textFieldID;
public Korisnici() {
connection = sqlConnection.dbConnector();
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 777, 512);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JButton btnLoadTable = new JButton("Load \"Korisnici\" table");
btnLoadTable.setFont(new Font("Tahoma", Font.BOLD, 14));
btnLoadTable.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "SELECT * FROM KORISNICI";
PreparedStatement pst= connection.prepareStatement(query);
ResultSet ps = pst.executeQuery();
table.setModel(DbUtils.resultSetToTableModel(ps));
} catch (Exception e) {
e.printStackTrace();
}
}
});
btnLoadTable.setBounds(411, 11, 211, 50);
contentPane.add(btnLoadTable);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(305, 83, 446, 311);
contentPane.add(scrollPane);
table = new JTable();
scrollPane.setViewportView(table);
JLabel lblId = new JLabel("ID");
lblId.setFont(new Font("Tahoma", Font.BOLD, 14));
lblId.setBounds(10, 83, 115, 60);
contentPane.add(lblId);
JLabel lblEmail = new JLabel("Email");
lblEmail.setFont(new Font("Tahoma", Font.BOLD, 14));
lblEmail.setBounds(10, 154, 115, 60);
contentPane.add(lblEmail);
JLabel lblName = new JLabel("Name");
lblName.setFont(new Font("Tahoma", Font.BOLD, 14));
lblName.setBounds(10, 225, 115, 60);
contentPane.add(lblName);
JLabel lblPhonenumber = new JLabel("Phone number");
lblPhonenumber.setFont(new Font("Tahoma", Font.BOLD, 14));
lblPhonenumber.setBounds(10, 296, 120, 60);
contentPane.add(lblPhonenumber);
textFieldPhoneNumber = new JTextField();
textFieldPhoneNumber.setBounds(135, 313, 155, 30);
contentPane.add(textFieldPhoneNumber);
textFieldPhoneNumber.setColumns(10);
textFieldName = new JTextField();
textFieldName.setBounds(135, 242, 155, 30);
contentPane.add(textFieldName);
textFieldName.setColumns(10);
textFieldEmail = new JTextField();
textFieldEmail.setBounds(135, 171, 155, 30);
contentPane.add(textFieldEmail);
textFieldEmail.setColumns(10);
textFieldID = new JTextField();
textFieldID.setBounds(135, 100, 155, 30);
contentPane.add(textFieldID);
textFieldID.setColumns(10);
JButton btnSave = new JButton("Save");
btnSave.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
try {
String query = "INSERT INTO korisnici (ID, EMAIL, NAME, PHONE_NUMBER) values (?, ?, ?, ?)";
PreparedStatement pst = connection.prepareStatement(query);
pst.setString(1, textFieldID.getText());
pst.setString(2, textFieldEmail.getText());
pst.setString(3, textFieldName.getText());
pst.setString(4, textFieldPhoneNumber.getText());
ResultSet rs = pst.executeQuery();
JOptionPane.showMessageDialog(null, "Data Saved");
pst.close();
rs.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnSave.setFont(new Font("Tahoma", Font.BOLD, 14));
btnSave.setBounds(10, 400, 90, 40);
contentPane.add(btnSave);
JButton btnUpdate = new JButton("Update");
btnUpdate.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
try {
String query = "UPDATE korisnici SET ID='"+textFieldID.getText()+"' ,email='"+textFieldEmail.getText()+"' ,name='"+textFieldName.getText()+"' ,Phone number='"+textFieldPhoneNumber.getText()+"' ";
PreparedStatement pst = connection.prepareStatement(query);
pst.execute();
JOptionPane.showMessageDialog(null, "Data Updated");
pst.close();
} catch (Exception e1) {
e1.printStackTrace();
}
}
});
btnUpdate.setFont(new Font("Tahoma", Font.BOLD, 14));
btnUpdate.setBounds(110, 400, 90, 40);
contentPane.add(btnUpdate);
}
}
The update:
String query = "UPDATE korisnici SET ID='"+textFieldID.getText()
+"' ,email='"+textFieldEmail.getText()+"',name='"+textFieldName.getText()
+"' ,Phone number='"+textFieldPhoneNumber.getText()+"' ";
constains this snippet:
.... ,Phone number='"+ .....
In Oracle nonquoted identifiers cannot contain spaces, see this:
https://docs.oracle.com/cd/B19306_01/server.102/b14200/sql_elements008.htm
Nonquoted identifiers can contain only alphanumeric characters from
your database character set and the underscore (_), dollar sign ($),
and pound sign (#). Database links can also contain periods (.) and
"at" signs (#). Oracle strongly discourages you from using $ and # in
nonquoted identifiers.
Quoted identifiers can contain any characters and punctuations marks
as well as spaces. However, neither quoted nor nonquoted identifiers
can contain double quotation marks or the null character (\0).
In other words: Phone number is treated as a column named Phone, and Oracle expects = after a column name in the update statement, but it gets number, then throws the error.

retrieve mysql data when i change combobox item in java

I use the following code to retrieve data from msysql database to a JComboBox. It was working properly. My problem is when I execute this code, if I click jCombobox, only one item is shown and it displays the related data from database.. it is not getting all the ids from database to Combobox, so that i can select a particular id and display related data.
package Swings;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.sql.*;
import javax.swing.*;
class Frame3 extends JFrame implements ActionListener,ItemListener
{
private JFrame frame;
JPanel panel=new JPanel();
JButton btn1,btn2,btn3;
JLabel l1, l2, l3, l4, l5, l6, l7;
private JComboBox SummonIdbox;
private JTextField txtcarLicenceNo;
private JTextField txtamount;
private JTextField txtdateFined;
private JTextField txtlocation;
private JTextField txtofficerInCharge;
String dbURL = "jdbc:mysql://localhost:3306/cpss";
String username ="root";
String password = "root";
Connection c = null;
Statement st = null;
ResultSet rs = null;
Frame3()
{
setVisible(true);
setSize(700, 700);
setLayout(null);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setTitle("CPSS Application");
l1 = new JLabel("Update Summon Details");
l1.setForeground(Color.blue);
l1.setFont(new Font("Serif", Font.BOLD, 20));
l2 = new JLabel("SummonId");
l3 = new JLabel("Car LicenceNo:");
l4 = new JLabel("Amount");
l5 = new JLabel("DateFined");
l6 = new JLabel("Location");
l7 = new JLabel("Officer Incharge");
SummonIdbox = new JComboBox();
txtcarLicenceNo = new JTextField();
txtamount = new JTextField();
txtdateFined = new JTextField();
txtlocation = new JTextField();
txtofficerInCharge=new JTextField();
btn1 = new JButton("Update");
btn2 = new JButton("Clear");
btn3= new JButton("Home");
btn1.addActionListener(this);
btn2.addActionListener(this);
btn3.addActionListener(this);
SummonIdbox.addItemListener(this);
l1.setBounds(500, 30, 400, 30);
l2.setBounds(400, 70, 200, 30);
l3.setBounds(400, 110, 200, 30);
l4.setBounds(400, 150, 200, 30);
l5.setBounds(400, 190, 200, 30);
l6.setBounds(400, 230, 200, 30);
l7.setBounds(400, 270, 200, 30);
SummonIdbox.setBounds(500, 70, 200, 30);
txtcarLicenceNo.setBounds(500, 110, 200, 30);
txtamount.setBounds(500, 150, 200, 30);
txtdateFined.setBounds(500, 190, 200, 30);
txtlocation.setBounds(500, 230, 200, 30);
txtofficerInCharge.setBounds(500, 270, 200, 30);
btn1.setBounds(450, 350, 100, 30);
btn2.setBounds(600, 350, 100, 30);
btn3.setBounds(750, 350, 100, 30);
add(l1);
add(l2);
add(SummonIdbox);
add(l3);
add(txtcarLicenceNo);
add(l4);
add(txtamount);
add(l5);
add(txtdateFined);
add(l6);
add(txtlocation);
add(l7);
add(txtofficerInCharge);
add(btn1);
add(btn2);
add(btn3);
add_summonid(SummonIdbox);
}
#Override
public void actionPerformed(ActionEvent ae ) {
if(ae.getSource() == btn2)
{
txtcarLicenceNo.setText("");
txtamount.setText("");
txtdateFined.setText("");
txtlocation.setText("");
txtofficerInCharge.setText("");
}
else if (ae.getSource() == btn3)
{
SwingMenu s=new SwingMenu();
s.setSize(800,800);
s.setVisible(true);
}
}
void add_summonid(JComboBox SummonIdbox)
{
try
{
//Class.forName("com.mysql.jdbc.Driver");
//System.out.println("Driver is loaded");
c = DriverManager.getConnection(dbURL, username, password);
System.out.println("Connection created");
st=c.createStatement();
rs=st.executeQuery("select Summonid from summon");
while(rs.next())
SummonIdbox.addItem(rs.getInt(1));
// c.close();
}
catch (Exception ex)
{
System.out.println(ex);
}
}
#Override
public void itemStateChanged(ItemEvent ie) {
int item= (Integer) SummonIdbox.getSelectedItem();
System.out.println(item);
String sql="select carLicenceNo,amount,dateFined,location,officerIncharge from summon where summonId='"+item+"'";
try {
PreparedStatement pst = c.prepareStatement(sql);
//pst.setInt(1,item);
rs=pst.executeQuery();
while(rs.next())
{
txtcarLicenceNo.setText(rs.getString(1));
txtamount.setText(String.valueOf((rs.getDouble(2))));
txtdateFined.setText(rs.getString(3));
txtlocation.setText(rs.getString(4));
txtofficerInCharge.setText(rs.getString(5));
/*System.out.println(rs.getString(1));
System.out.println(rs.getDouble(2));
System.out.println(rs.getString(3));
System.out.println(rs.getString(4));
System.out.println(rs.getString(5));*/
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}

how to exit upper frame by click on ok and how to add back button when two page in single frame

import javax.swing.*;
import java.awt.*;
import java.awt.event.*;
import java.sql.*;
public class Prhr extends JFrame implements ActionListener,ItemListener
{
JLabel l1;
JLabel l2;
JTextField ar;
JTextField t;
JButton b1;
JButton b2;
JButton b3,b4;
JComboBox c1,c2;
JLabel l3;
Connection con;
Statement st;
JLabel l4;
JLabel l5;
JLabel l6;
JLabel l7,l8,l9,l10,l11,l12,l13;
Font f,f2,f1;
String s3,s4;
public Prhr()
{
c1=new JComboBox();
c1.addItem("....");
//*****************************************
try{
System.out.println("in");
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/amit","root","1234");
System.out.println(con);
st=con.createStatement();
System.out.println(st);
ResultSet rs= st.executeQuery("select * from CHR");
while(rs.next())
{
c1.addItem(rs.getString("prnm"));
}
}catch(Exception e1)
{
e1.printStackTrace();
}
//****************************************
//JPanel p=new JPanel();
//j.add(p);
f2=new Font("Tahoma", 1, 20);
setFont(f2);
setTitle("CREATE PROCESS HIERARCHY");
f1=new Font("Tahoma", 1, 18);
//setFont(f1);
l1=new JLabel("Process Name");
l2=new JLabel("Description");
l3=new JLabel("Provide Process Detail");
l8=new JLabel("Parent Process");
l9=new JLabel("Processs Type");
ar=new JTextField();
t=new JTextField();
c2=new JComboBox();
b1=new JButton("Preview & Save");
b2=new JButton("Clear");
b3=new JButton("Save as Draft");
setLayout(null);
f=new Font("Tahoma", 1, 20);
//c1.addItem("....");
c2.addItem("Process");
//c1.addItem("1c1");
//c1.addItem("2c1");
c2.addItem("Activity");
//c2.addItem("2c2");
add(l3);
l3.setBounds(170, 70, 250, 20);
add(l1);
l3.setFont(f1);
l1.setBounds(100,130,100,20);
add(t);
t.setBounds(210, 130, 200, 20);
add(l2);
l2.setBounds(100, 175, 100, 20);
add(l8);
l8.setBounds(100, 240, 100, 20);
add(l9);
l9.setBounds(100, 285, 100, 20);
add(ar);
ar.setBounds(210, 175, 200, 40);
add(c1);
c1.setBounds(210, 240, 200, 20);
add(c2);
c2.setBounds(210, 285, 200, 20);
add(b1);
b1.setBounds(50, 365, 129, 20);
add(b2);
b2.setBounds(220, 365, 70, 20);
add(b3);
b3.setBounds(340, 365, 120, 20);
b1.addActionListener(this);
b2.addActionListener(this);
b3.addActionListener(this);
c1.addItemListener(this);
c2.addItemListener(this);
t.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= 65) && (c <= 90)||(c>=97)&&(c<=122) ||
/*(c == KeyEvent.VK_BACK_SPACE) ||*/(c==32)||
(c == KeyEvent.VK_DELETE))) {
// getToolkit().beep();
e.consume();
}
}
});
ar.addKeyListener(new KeyAdapter() {
public void keyTyped(KeyEvent e) {
char c = e.getKeyChar();
if (!((c >= 65) && (c <= 90)||(c>=97)&&(c<=122) ||
/*(c == KeyEvent.VK_BACK_SPACE) ||*/(c==32)
)) {
// getToolkit().beep();
e.consume();
}
}
});
//b4.addActionListener(this);
}
public void itemStateChanged(ItemEvent ie)
{
s3=(String)c1.getSelectedItem();
System.out.println(s3);
s4=(String)c2.getSelectedItem();
System.out.println(s4);
}
public void actionPerformed(ActionEvent a)
{
if(a.getSource()==b1)
{
System.out.println("in b1");
final String s1=t.getText();
final String s2=ar.getText();
int q=s1.length();
int w=s2.length();
if(q<=20||q>0&&w<=200||w>0)
{
System.out.println(s3);
System.out.println(s4);
JFrame j=new JFrame();
j.setVisible(true);
//j.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
j.setSize(500,500);
JPanel p=new JPanel();
j.add(p);
p.setLayout(null);
l4=new JLabel("Process Name");
l5=new JLabel(s1);
l6=new JLabel("Description");
l7=new JLabel(s2);
l10=new JLabel("Parent Process");
l11=new JLabel(s3);
l12=new JLabel("Process Type");
l13=new JLabel(s4);
b4=new JButton("OK");
p.add(l4);
l4.setBounds(100,130,100,20);
p.add(l5);
l5.setBounds(210, 130, 200, 20);
p.add(l6);
l6.setBounds(100, 175, 100, 20);
p.add(l7);
l7.setBounds(210, 175, 200, 40);
p.add(l10);
l10.setBounds(100, 240, 100, 20);
p.add(l11);
l11.setBounds(210, 240, 200, 20);
p.add(l13);
l13.setBounds(210, 285, 200, 20);
p.add(l12);
l12.setBounds(100, 285, 100, 20);
p.add(b4);
b4.setBounds(220, 365, 70, 20);
//**************88
b4.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent d) {
if(d.getSource()==b4)
{
//System.exit(1);
dispose();
try
{
dispose();
System.out.println("in");
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/amit","root","1234");
System.out.println(con);
st=con.createStatement();
System.out.println(st);
int i=st.executeUpdate("insert into CHR values('"+s1+"','"+s2+"','"+s3+"','"+s4+"')");
if(i>1)
{
con.close();
st.close();
}
//setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
System.out.println("inserted");
ResultSet rs= st.executeQuery("select * from CHR");
while(rs.next())
{
c1.addItem(rs.getString("prnm"));
}
}catch(Exception e)
{
e.printStackTrace();
}
//j.dispose();
}//b4 if close
}
});
}
else
{
String message = "\"Pls enter Name within 20 Chatarter\"\n"
+ "OR\n"
+ "Pls enter Description within 200 character";;
JOptionPane.showMessageDialog(new JFrame(), message, "Dialog",
JOptionPane.ERROR_MESSAGE);
}
}
else if (a.getSource()==b2)
{
System.out.println("in b2");
t.setText("");
ar.setText("");
c1.setSelectedItem("....");
c2.setSelectedItem("Process");
}
else if(a.getSource()==b3)
{
System.out.println("in b3");
}
}
public static void main(String args[])
{
Prhr pr=new Prhr();
pr.setVisible(true);
pr.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
pr.setSize(500,500);
}
}
I see in your actionPerformed method you are creating a new JFrame. I assume that is the second frame you are talking about. You might want to use a JDialog, but hard to say since I've no idea what your app does.
But to answer your question, to close a JFrame call:
j.setVisible(false);

Categories