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.
Related
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) {
}
}
}
I have this code and I can't get it to run. I'm new with JAVA. I was trying to make a login and registration form with JAVA swing, and I finished designing GUI part and I also connected the code with mySQL database. But I don't know why that I can't run the code. I tried debugging it, but can't find the bug. I am using eclipse and I also referenced mySQL jar.
Please let me know, if I'm doing anything wrong. Thank you for the help :)
package login_register_form;
import java.awt.Color;
import java.awt.EventQueue;
import java.awt.Font;
import java.awt.Image;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.JOptionPane;
import javax.swing.JButton;
import java.sql.*;
import javax.swing.JComboBox;
public class RegisterPage implements ActionListener{
JFrame frame;
String[] position = {"Admin", "Manager", "Assistant"};
JTextField firstName;
JTextField lastName;
JTextField userName;
JTextField email;
JPasswordField password;
JPasswordField confirmPW;
JButton registerButton;
JButton cancelButton;
JComboBox jobPosition = new JComboBox(position);
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
RegisterPage window = new RegisterPage();
window.frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application. Calling methods from constructor
*/
public RegisterPage() {
createWindow();
initialize();
actionEvent();
}
/**
* Create a main window
*/
public void createWindow() {
frame = new JFrame();
frame.setTitle("Registration Page");
frame.getContentPane().setBackground(Color.GRAY);
frame.setBounds(100, 100, 1113, 806);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.getContentPane().setLayout(null);
}
/**
* Initialize the contents of the frame.
*/
private void initialize() {
// panel: orange colored background
JPanel panel = new JPanel();
panel.setBackground(new Color(255,165,0,200));
panel.setBounds(300, 150, 500, 472);
frame.getContentPane().add(panel);
panel.setLayout(null);
// label: scaled background
JLabel background = new JLabel("");
background.setBounds(6, 6, 1100, 772);
ImageIcon icon = new ImageIcon(this.getClass().getResource("/background.jpg"));
Image img = icon.getImage();
Image imgScale = img.getScaledInstance(background.getWidth(), background.getHeight(), Image.SCALE_SMOOTH);
ImageIcon scaledIcon = new ImageIcon(imgScale);
background.setIcon(scaledIcon);
frame.getContentPane().add(background);
// title: "Register Page"
JLabel registerPage = new JLabel("Register Page");
registerPage.setFont(new Font("Lucida Grande", Font.BOLD, 19));
registerPage.setBounds(182, 40, 135, 29);
panel.add(registerPage);
// input: first name
firstName = new JTextField();
firstName.setBounds(145, 76, 210, 32);
panel.add(firstName);
firstName.setColumns(10);
// input: last name
lastName = new JTextField();
lastName.setBounds(145, 120, 210, 32);
panel.add(lastName);
lastName.setColumns(10);
// input: user name
userName = new JTextField();
userName.setBounds(145, 164, 210, 32);
panel.add(userName);
userName.setColumns(10);
// input: password
password = new JPasswordField();
password.setBounds(145, 208, 210, 32);
panel.add(password);
// input: confirm password
confirmPW = new JPasswordField();
confirmPW.setBounds(145, 252, 210, 32);
panel.add(confirmPW);
// input: email
email = new JTextField();
email.setBounds(145, 296, 210, 32);
panel.add(email);
email.setColumns(10);
// input: position
jobPosition.setBounds(145, 340, 210, 32);
panel.add(jobPosition);
// button: cancel
JButton cancelButton = new JButton("Cancel");
cancelButton.setBounds(109, 400, 117, 40);
panel.add(cancelButton);
// button: register
JButton registerButton = new JButton("Register");
registerButton.setBounds(275, 400, 117, 40);
panel.add(registerButton);
// label: first name
JLabel fName = new JLabel("First Name");
fName.setBounds(36, 84, 85, 16);
panel.add(fName);
// label: last name
JLabel lName = new JLabel("Last Name");
lName.setBounds(36, 128, 85, 16);
panel.add(lName);
// label: user name
JLabel uName = new JLabel("User Name");
uName.setBounds(36, 172, 85, 16);
panel.add(uName);
// label: password
JLabel pWord = new JLabel("Password");
pWord.setBounds(36, 216, 85, 16);
panel.add(pWord);
// label: re-password
JLabel cPW = new JLabel("Re-Password");
cPW.setBounds(36, 260, 85, 16);
panel.add(cPW);
// label: email
JLabel eMail = new JLabel("Email");
eMail.setBounds(36, 304, 85, 16);
panel.add(eMail);
// label: position
JLabel position = new JLabel("Position");
position.setBounds(36, 347, 101, 16);
panel.add(position);
}
public void actionEvent() {
// Adding action listener to buttons
registerButton.addActionListener(this);
cancelButton.addActionListener(this);
}
#Override
public void actionPerformed(ActionEvent e) {
if (e.getSource()==registerButton) {
try {
//Creating Connection Object
Connection connection=DriverManager.getConnection("jdbc:mysql://localhost:3306/myDatabase","root", "root");
//Prepared Statement
PreparedStatement Pstatement=connection.prepareStatement("insert into student value(?,?,?,?,?,?)");
// Specifying the values of it's parameter
Pstatement.setString(1, firstName.getText());
Pstatement.setString(2, lastName.getText());
Pstatement.setString(3, userName.getText());
Pstatement.setString(4, password.getText());
Pstatement.setString(5, confirmPW.getText());
Pstatement.setString(6, email.getText());
Pstatement.setString(7, jobPosition.getSelectedItem().toString());
//Checking for the password match
if (password.getText().equalsIgnoreCase(confirmPW.getText())) {
// Executing query
Pstatement.executeUpdate();
JOptionPane.showMessageDialog(null, "Data Registered Successfully");
} else {
JOptionPane.showMessageDialog(null, "Password did not match");
}
} catch (SQLException e1) {
e1.printStackTrace();
}
}
if (e.getSource()==cancelButton) {
// Clearing Fields
firstName.setText("");
lastName.setText("");
userName.setText("");
password.setText("");
confirmPW.setText("");
email.setText("");
jobPosition.setSelectedItem("Admin");
}
}
}
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm trying to add input to my database through the use of my GUI and MYSQL code. But i keep getting "java.lang.NullPointerException" And it probably isn't the last error after that has been fixed.. Anyway. The button press is supposed to take the input from the textboxes that you input, and send it to the database, but it doesn't quite work.
Can you help me? The problem is somewhere in the actionPerformed method
(You can copy paste the code and run it directly if it would help)
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);
}
}
}
}
In most probability you have problem connecting to DB, so your connection object "con" is null hence the
java.lang.NullPointerException
java:119
at PreparedStatement preparedStatement=con.prepareStatement(sql);
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();
}
}
}
I'm having a problem with my code in java. It is supposed to insert data into a database but it's returning a nullpointerexception. Here is my code.
package client;
import java.sql.*;
import java.awt.Desktop;
import java.awt.EventQueue;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.util.*;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JFrame;
import javax.swing.JTextField;
import javax.swing.JLabel;
import javax.swing.JComboBox;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JOptionPane;
public class AddCon {
private Connection conn;
private JFrame frmAddContract;
private JTextField ContractNo;
private JTextField EngagerName;
private JTextField contNo;
private JTextField month;
private JTextField day;
private JTextField year;
private JTextField tme;
private JTextField cladd;
private JTextField eventadd;
private JTextField textField_fp;
private JTextField refer;
/**
* Launch the application.
*/
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
AddCon window = new AddCon();
window.frmAddContract.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
/**
* Create the application.
*/
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/KusinaNiKambal","root","1234");
Statement stmt = null;
stmt = conn.createStatement();}
catch (Exception e){
JOptionPane.showMessageDialog(null, e);}
/**
* Initialize the contents of the frame.
*/
initialize();
}
private void initialize() {
frmAddContract = new JFrame();
frmAddContract.setResizable(false);
frmAddContract.setTitle("Add Contract");
frmAddContract.setBounds(100, 100, 450, 640);
frmAddContract.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frmAddContract.getContentPane().setLayout(null);
ContractNo = new JTextField();
ContractNo.setBounds(38, 32, 152, 20);
frmAddContract.getContentPane().add(ContractNo);
ContractNo.setColumns(10);
JLabel lblContract = new JLabel("Contract #");
lblContract.setBounds(38, 18, 76, 14);
frmAddContract.getContentPane().add(lblContract);
JLabel lblEngager = new JLabel("Engager");
lblEngager.setBounds(38, 63, 48, 14);
frmAddContract.getContentPane().add(lblEngager);
EngagerName = new JTextField();
EngagerName.setBounds(38, 78, 152, 20);
frmAddContract.getContentPane().add(EngagerName);
EngagerName.setColumns(10);
contNo = new JTextField();
contNo.setBounds(38, 128, 152, 20);
frmAddContract.getContentPane().add(contNo);
contNo.setColumns(10);
JLabel lblNewLabel = new JLabel("Contact #");
lblNewLabel.setBounds(38, 109, 86, 14);
frmAddContract.getContentPane().add(lblNewLabel);
month = new JTextField();
month.setBounds(38, 255, 116, 20);
frmAddContract.getContentPane().add(month);
day = new JTextField();
day.setBounds(181, 255, 81, 20);
frmAddContract.getContentPane().add(day);
year = new JTextField();
year.setBounds(294, 255, 86, 20);
frmAddContract.getContentPane().add(year);
year.setColumns(10);
JLabel lblMonth = new JLabel("Month in number format");
lblMonth.setBounds(38, 236, 100, 14);
frmAddContract.getContentPane().add(lblMonth);
JLabel lblDay = new JLabel("Day");
lblDay.setBounds(181, 236, 48, 14);
frmAddContract.getContentPane().add(lblDay);
JLabel lblYear = new JLabel("Year");
lblYear.setBounds(294, 236, 48, 14);
frmAddContract.getContentPane().add(lblYear);
JLabel lblEventDate = new JLabel("Event Date");
lblEventDate.setBounds(38, 222, 76, 14);
frmAddContract.getContentPane().add(lblEventDate);
tme = new JTextField();
tme.setBounds(38, 307, 59, 20);
frmAddContract.getContentPane().add(tme);
tme.setColumns(10);
cladd = new JTextField();
cladd.setBounds(38, 180, 363, 31);
frmAddContract.getContentPane().add(cladd);
cladd.setColumns(10);
JLabel lblAddress = new JLabel("Client Address");
lblAddress.setBounds(38, 159, 98, 14);
frmAddContract.getContentPane().add(lblAddress);
JLabel lblTime = new JLabel("Time");
lblTime.setBounds(38, 286, 60, 14);
frmAddContract.getContentPane().add(lblTime);
eventadd = new JTextField();
eventadd.setBounds(38, 358, 373, 50);
frmAddContract.getContentPane().add(eventadd);
eventadd.setColumns(10);
JLabel lblEventAddress = new JLabel("Event Address");
lblEventAddress.setBounds(38, 338, 116, 14);
frmAddContract.getContentPane().add(lblEventAddress);
textField_fp = new JTextField();
textField_fp.setBounds(38, 454, 276, 20);
frmAddContract.getContentPane().add(textField_fp);
textField_fp.setColumns(10);
JLabel lblFilepathOfContract = new JLabel("Filepath of Contract - the PDF file");
lblFilepathOfContract.setBounds(38, 431, 116, 14);
frmAddContract.getContentPane().add(lblFilepathOfContract);
JButton btnBrowse = new JButton("Browse...");
btnBrowse.setBounds(324, 453, 89, 23);
frmAddContract.getContentPane().add(btnBrowse);
btnBrowse.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
final JFileChooser fc = new JFileChooser();
int returnVal = fc.showOpenDialog(null);
String filepath = fc.getSelectedFile().getAbsolutePath();
textField_fp.setText(filepath);
}
});
refer = new JTextField();
refer.setBounds(38, 510, 276, 20);
frmAddContract.getContentPane().add(refer);
refer.setColumns(10);
JLabel lblEncodedBy = new JLabel("Referred By");
lblEncodedBy.setBounds(38, 485, 116, 14);
frmAddContract.getContentPane().add(lblEncodedBy);
JButton btnAdd = new JButton("Add");
btnAdd.setBounds(101, 560, 89, 23);
frmAddContract.getContentPane().add(btnAdd);
btnAdd.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
try{
String cntr = ContractNo.getText();
String en = EngagerName.getText();
String cont = contNo.getText();
String mo = month.getText();
String d = day.getText();
String yr = year.getText();
String dte = yr + "-" + mo + "-" + d;
String cla = cladd.getText();
String tm = tme.getText() + ":00";
String evadd = eventadd.getText();
String filepath = textField_fp.getText();
String ref = refer.getText();
String SQL = "insert into cis "+
"values ('"+cntr+"','"+en+"','"+
cont+"','"+cla+"' '"+dte+"','"+tm+"','"+
evadd+"','"+filepath+"','"+ref+")";
PreparedStatement stmt = conn.prepareStatement(SQL);
ResultSet rs = stmt.executeQuery();
}
catch(Exception e){
JOptionPane.showMessageDialog(null, e);
}
}
});
JButton btnCancel = new JButton("Cancel");
btnCancel.setBounds(225, 560, 89, 23);
frmAddContract.getContentPane().add(btnCancel);
btnCancel.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent ae) {
frmAddContract.setVisible(false);
}
});
}
}
Sorry, i'm not really that experienced in java programming and this is my first time making a code for querying databases.
You do never initialize your conn instance variable. This will lead to a NullPointerException (at least) in this line:
PreparedStatement stmt = conn.prepareStatement(SQL);
^------------ NEVER INITIALIZED
public class AddCon {
private Connection conn;
...
// constructor
public AddCon() {
try{
//Load database driver and connect
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection(<your parameters>);
^----------- MISTAKE
...
In the above code you create a connection, but instead of assigning it to the instance variable you just use a local variable. Replace that line with:
this.conn = DriverManager.getConnection(<your parameters>);
Edit: Please always post the stacktrace in case of exceptions!