我在将日期从JDateChooser存储到MySQL数据库时遇到问题

时间:2014-09-06 04:26:22

标签: java mysql jdatechooser

我在将数据从GUI传递到MySQL数据库时遇到问题。我正在从JTextFieldJDateChooser收集信息到数据库中。除日期外,其他所有工作都有效。我尝试了在网上找到的多种方法,但没有一种方法有效。我还检查了表格,以确保" DATE"数据类型在我的" patientinfo"中启用表。如果我删除JDateChooser,我的查询工作。否则,我将收到以下错误消息:

显示java.lang.NullPointerException

我在此消息中包含了我的源代码。

//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.

2 个答案:

答案 0 :(得分:1)

java.sql.Date date = new java.sql.Date(dateChooser.getDate().getTime());

Date转换为sql对象,然后存储在数据库中。希望它能奏效。

答案 1 :(得分:1)

尝试这样的事情 将您输入的java.util.Date转换为java.sql.Date,将其存储到Mysql数据库,因为mysql以[{1}}

格式存储Date
yyyy-MM-dd

然后按照他的方式行事

public static java.sql.Date convertUtilDateToSqlDate(java.util.Date date){
    if(date != null) {
        java.sql.Date sqlDate = new java.sql.Date(date.getTime());
        return sqlDate;
    }
    return null;
}

我希望你能做必要的异常处理和连接关闭