I want to insert valued from JForm to mysql database. But I can't insert values to date field.. This code is working except for date field. Can someone help me..
String s1=txtUsername.getText();
String s2=txtPassword.getText();
String s3=txtName.getText();
String s4=txtAddress.getText();
String s5=txtContractEndDetails.getText();
connection getcon = new connection();
Connection conn;
try{
conn=getcon.creatConnection();
String sql="insert into TravelGuide(username,password,name,address,contract_end_date)values(?,?,?,?,?)";
PreparedStatement stmt = conn.prepareStatement(sql);
java.sql.Date dtValue = java.sql.Date.valueOf(s5);
stmt.setString(1, s1);
stmt.setString(2, s2);
stmt.setString(3, s3);
stmt.setString(4, s4);
stmt.setDate(5, s5);
stmt.executeUpdate();
}
catch(Exception ex){
JOptionPane.showMessageDialog(PanelTG, ex.getMessage(),"Error Occured 123",2);
}
In order to turn a string into a java.util.Date
object, you need a DateFormat
(eg SimpleDateFormat
)
dateFormat.parse(..)
to turn the string into a Date
.Since you are using MySQL DB for that you need to Format your s5 variable string to yyyy-mm-dd date. You can format it using dateFormat. Or make sure your s5 variable should contain string like this '2000-06-30'
You need to pass a java.util.Date
. You can parse a Date
from a String
using a SimpleDateFormat
.
Your code could look like this:
String s5 = txtContractEndDetails.getText();
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
Date contractEndDate = null;
try {
contractEndDate = simpleDateFormat.parse(s5);
} catch (ParseException e) {
// handle telling the user they have bad input
}
stmt.setDate(5, contractEndDate);
Notes:
s1
, s2
etc. They lead to unreadability, and thus bugs: Either use proper names like name
, address
etc, or in-line them (ie remove them and directly use the code that initialized them instead)public class Test {
public static void main(String[] args){
Date date = new Date();
DateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
String newDate = simpleDateFormat.format(date);
System.out.println("DateIn String datatype = "+newDate);
System.out.println("DateIn Date datatype = "+java.sql.Date.valueOf(newDate));
}
}
Let Me give u basic go throw how to convert String type data ie we got from Web page/HTML page and the data is been processed in java and then insert it into DB of Mysql. Below is just a piece of code.
String d = req.getParameter("dob");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-mm-dd");
java.util.Date convertedDate = formatter.parse(d);
java.sql.Date date1 = new java.sql.Date(convertedDate.getTime());
prestat.setDate(3, date1);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.