I have problems storing Date from JDateChooser into MySQL database

Federico Chin picture Federico Chin · Sep 6, 2014 · Viewed 10.7k times · Source

I am having problems passing data from my GUI to MySQL database. I am collecting information from JTextFields and JDateChooser, into the database. Everything else works, except the date. I tried multiple methods that I found online, and none of them have worked. I also checked the table, to ensure that the "DATE" data type is enabled in my "patientinfo" Table. If I remove the JDateChooser, my query works. Otherwise, I will get this error message:

Java.lang.NullPointerException

I am including my source code with this message.

//Event handler adds records
//to the database

JButton subInfoBtn = new JButton("SUBMIT AND CONTINUE");

subInfoBtn.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent arg0) {

            try {
                //Invokes "javaconnect" class
                //to link to MySQL database
                conn = javaconnect.ConnecrDb();

                //Invokes SQL Statement from "Connection" Object
                pst = conn.createStatement();

                //SQL query commands event handler to access
                //"patientinfo" table, to insert data to columns.
                pst.executeUpdate("INSERT into patientinfo(firstName, lastName, DOB, age, SSN, "
                                  + "address, phone,email, emergencycontact, emergencyphone) "
                                  + "VALUES" + "('"+firstTxt.getText() + "', '" + lastTxt.getText()
                                  + "', '" + DOBTxt.getDate() + "' ,'" + ageTxt.getText() + "', '"
                                  + ssnTxt.getText() + "', "+ " '" + addressTxt.getText() +"',
                                  '"+phoneTxt.getText()+"'  , '"+emailTxt.getText()+"'  ,
                                  '"+emergencyTxt.getText()+"'  , '"+emergPhoneTxt.getText()+"'  )");


                //Closes Database Connection
                conn.close();
                JOptionPane.showMessageDialog(null, "Pantient Information Saved Succesfully");

            } catch (Exception e) {
                JOptionPane.showMessageDialog(null, e);
            }
        }
    });

    subInfoBtn.setFont(new Font("Tahoma", Font.BOLD, 14));
    subInfoBtn.setBounds(305, 286, 220, 23);
    contentPane.add(subInfoBtn);

//Also, I have tried to use SimpleDateFormat and
//((JTextField)jDateChooser1.getDateEditor().getUiComponent()).getText();
//Without any luck.  I am also aware of using Prepare Statement to avoid SQL injections, but
//I would like to solve the JDateChooser bonding data dilema into MySQL database.

Answer

Ishwar Surywanshi picture Ishwar Surywanshi · Sep 6, 2014
java.sql.Date date = new java.sql.Date(dateChooser.getDate().getTime());

Convert Date to sql object then store in database. Hope it will work.