我在将数据从GUI传递到MySQL数据库时遇到问题。我正在将JTextField
和JDateChooser
的信息收集到数据库中。除日期外,其他一切都有效。我尝试了在网上找到的多种方法,但都没有奏效。我还检查了该表,以确保在我的"patientinfo"表中启用了"DATE"数据类型。如果我删除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.
试试这样的东西将您输入的java.util.Date转换为java.sql.Date,以便将其存储到Mysql数据库中,因为Mysql存储格式为yyyy-MM-dd
的Date
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;
}
然后按照他的方式
PreparedStatement statement = conn.prepareStatement("INSERT INTO patientinfo"+
"(firstName, lastName, DOB, age, SSN, address," +
"phone,email, emergencycontact, emergencyphone)"+
"VALUES(?,?,?,?,?,?,?,?,?,?)");
statement.setTimestamp(1,sqlDate);
statement.setString(1,firstTxt.getText());
statement.setString(2,lastTxt.getText());
statement.setDate(3,convertUtilDateToSqlDate(DOBTxt.getDate()));
statement.setString(4,ageTxt.getText());
statement.setString(5,ssnTxt.getText());
statement.setString(6,addressTxt.getText());
statement.setString(7,phoneTxt.getText());
statement.setString(8,emailTxt.getText());
statement.setString(9,emergencyTxt.getText());
statement.setString(10,emergPhoneTxt.getText());
int i = statement.executeUpdate();
if(i>0){
System.out.println("Successfull");
}
我希望你能做必要的异常处理和连接关闭
java.sql.Date date = new java.sql.Date(dateChooser.getDate().getTime());
将Date
转换为sql对象,然后存储在数据库中。希望它能起作用。