I have a JSP page, so the user can insert the time when he/she arrives and goes from the place manually.
My question is: how can I convert that String, from the input box (JSP) to then insert it to query thus into my MySQL table.
I am using Java - servlet.
Thanks
You can use SimpleDateFormat to parse a String in the given pattern to a java.util.Date object.
Assuming that it's HH:mm, then you can do so:
String time = request.getParameter("time");
Date date = null;
try {
date = new SimpleDateFormat("HH:mm").parse(time);
}
catch (ParseException e) {
request.setAttribute("time_error", "Please enter time in format HH:mm");
}
Once having the java.util.Date object, you can store it in a TIME column by converting it to java.sql.Time and using PreparedStatement#setTime().
preparedStatement = connection.prepareStatement("INSERT INTO tablename (columname) VALUES (?)");
preparedStatement.setTime(1, new Time(date.getTime()));
preparedStatement.executeUpdate();
Related
I'm trying to get the data stored in database by getting the date then populate the table.
List<String> contents = new ArrayList<>();
List<Record> records
try {
Session session = sessionFactory.getCurrentSession();
Query<World> query = null;
query = session.createQuery("from World where date like :dateCont, World.class);
query.setParameter("dateCont", "%" + contents.get(0) + "%");
worlds = query.getResultList();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
The problem here is that it gives me an error exception:
java.lang.ClassCastException: class java.lang.String cannot be cast to
class java.util.Date (java.lang.String and java.util.Date are in
module java.base of loader 'bootstrap')
I know what's wrong because the List<String> contents values are string and needed to be converted to Date but I tried so many codes and it doesn't work.
//The following are the codes that I tried but it won't work:
//FIRST
Date date = new SimpleDateFormat("MM/dd/yyyy").parse(contentsStart.get(0));
new SimpleDateFormat("yyyy-MM-dd").format(date);
//---------------------------------------
//SECOND
Date newDate;
DateFormat formatter = null;
formatter = new SimpleDateFormat("yyyy-MM-dd");
newDate = (Date) formatter.parse(contentsStart.get(0));
So, is there any way to change the given value to date but it should retains the format "yyyy-MM-dd" and the datatype should be Date.
PS: the format of date in database is "yyyy-MM-dd" also.
Both my date entity field and date from DB is both Date as their
datatype.
Try this:
DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
Date d1= (Date) format.parse(yourDate);
You can use like operator only on string (VARCHAR) fields. In the WHERE clause you have to convert your field to string (using format function) in order to be able to use LIKE. So you have to call the convert function (also) IN THE QUERY.
Unfortunately, there are no DATE-functions in EJBQL, so you will have to switch to the native query. For example, for Oracle you can use TO_CHAR like this
SELECT ... WHERE TO_CHAR(date, 'MM/DD/YYYY') LIKE ...
For good performance you will have to add a functional index.
See also http://www.sqlines.com/oracle-to-sql-server/to_char_datetime
One alternative would be to add a new string column date_string, that will contain the formatted representation of your date and use this column with LIKE. But you will have to make absolutely sure, that both dates are always synchronized.
Is there any way to store the below date in mysql table
Date = 2017-01-05T00:00:00+05:30
//Table
create table test(dob DATETIME);
//Insert
insert into test(dob) values ('2017-01-05T00:00:00+05:30') // Throws error saying Incorrect datetime
Is there way I can insert the below date in mysql db from java code.
If you have a Date object, good. Otherwise, parse the string into a Date object using SimpleDateFormat like this:
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssXXX");
Date d = sdf.parse("2017-01-05T00:00:00+05:30");
Then you can make a PreparedStatement to do the date insert like this:
PreparedStatement ps = conn.prepareStatement("insert into test(dob) values (?)");
ps.setDate(1, new java.sql.Date(d.getTime()));
ps.executeUpdate();
I am new to java GUI
I have a form for simple data input that saved to mySQL. Among the textboxes I have defined is dateOfBirth.
In mySQL, the dateOfBirth column is type DATE.
When I attempt to save my record, I get incompatible conversions. How Do I handle this? The Date fields are DOR and DOB.
I tried to define a format :
DateFormat df= new SimpleDateFormat("dd/MM/yyyy");
and also changed redefined the var DOR or DOB as String:
String DOB = new String();
then when inserting into database, formatted the var like this:
df.format(DOB)
I still got the error: "Error: Cannot format given object as a Date". What to do?
String query = "INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy)"
+"VALUES('"+memberID+"','"+familyName+"','"+baptismName+"','"+DOR+"','"+DOB+"','"+fatherName+"','"+motherName+"','"+gender+"','"+memberType+"','"+address+"','"+residence+"','"+city+"','"+operator+"')";
con.UpDate(query);
First of all i would not use that query for the insert. You should use a prepared statement. It's safer against sql injection.
PreparedStatement ps =
connection.prepareStatement("INSERT INTO members (MemberID,FamilyName,BaptismName,DateOfRegistration,DateOfBirth,FatherName,MotherName,gender,MemberType,Address,Residence,City,CreatedBy) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)");
ps.setString(1, memberID); //or the correct type if not String
ps.setString(2, familyName);
ps.setString(3,baptismName);
DateFormat df= new SimpleDateFormat("dd/MM/yyyy"); //this the the format in which the user enters the date in the textbox. they have to input a string like 12/31/2014
java.util.Date date=df.parse(DOB); //DateFormat class has a method called parse which returns a java.util.Date object
ps.setDate(4, new java.sql.Date(date.getTime()));
//PreparedStatement class method setDate takes 2 parameters
//first is the index of the parameter in the prepared statement, and the second
//is java.sql.Date object.
//use constructor of java.sql.Date which takes a long parameter to create this object
//java.util.Date getTime() method returns a long value representing the date object
//so basically you convert string DOB to java.Util.Date,
//then convert java.Util.Date object to java.sql.Date needed by prepared statement
...
ps.executeUpdate();
I am trying to insert records from excel file into database table. The excel file contains time stamp as "05/10/13 03:47 PM IST". I want to save the time stamp in db as datetime, so that later i may able to fire query on datetime constraint. In java i am using prepared statement. I am using datetime2(7) data type in table.
value of timeStampt = 05/10/13 03:47 PM IST
private void insertToDb(String vh, String timeStamp, String location, double tempReal, double tempFixed) throws ParseException{
conn = DbHandler.getConnection();
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yy hh:mm a");
java.util.Date utilDate = sdf.parse(timeStamp);
java.sql.Date sqlDate = new java.sql.Date(utilDate.getTime());
String query = "INSERT INTO [DATALOGGER_TEMP_REPORT](vehicle_no,time_stamp,location,temp_real,temp_fixed)values(?,?,?,?,?)";
try {
pstmt= conn.prepareStatement(query);
pstmt.setString(1,vh);
pstmt.setDate(2, sqlDate);//(2, date);
pstmt.setString(3, location );
pstmt.setDouble(4, tempReal);
pstmt.setDouble(5, tempFixed);
pstmt.executeUpdate(); // execute insert statement
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
Currently, In database table timestamp value is stored as = 2013-10-05 00:00:00.0000000
Rather, i want my table to store timestamp as 05/10/13 03:47 PM IST
The problem here depends on what type of column you are trying to store into in the sql server db.
see http://msdn.microsoft.com/en-us/library/ms186724.aspx
If you are simply using a SQL Date type, then this only has the accuracy of one day.
I am assuming that the java.util.Date utilDate is correctly holding the datetime.
Try it with the java.sql.Timestamp type instead of java.sql.Date. This should be appropriate. It works the same way as with java.sql.Date.
Your code would then contain:
....
java.sql.Timestamp sqlTS = new.java.sql.Timestamp(utilDate.getTime());
...
pstmt.setTimestamp(2, sqlTS);
...
I am looking for a way to get today's date and pass to sql table and save there. Call the saved date and do some task with JODA TIME API. The changed Joda time Date to sql table and save there and process continues..
I tried this way,
//prints todays date
java.sql.Date sqlDate = new java.sql.Date(new Date().getTime());
//passes wrong date to the table like 1970-07-01 instead of 2013-03-01
String insert = "INSERT INTO TEST_TABLE VALUES(1,"+sqlDate+")";
pStmt = conn.prepareStatement(insert);
pStmt.executeUpdate();
//converting to joda time
LocalDate ld = new LocalDate(sqlDate);
//some calculations, and how to convert back to sql date?
What I am trying to do here is, A table with 3 columns (id, startdate, finishdate). id will be entered by user, start date should be automatically entered todays date. after some calculations with joda time and finish date will be set to date it is finished.
Code
String insert = "INSERT INTO TEST_TABLE VALUES(2,'"+timestamp+"')";
Error
Data type mismatch in criteria expression
//I have created table using MS access
//the format of the date column is Date/Time.
You Can use Timestamp here. java.sql.Timestamp extends java.util.Date, so anything you can do with a java.util.Date you can also do with a java.sql.Timestamp.
To convert LocalDateTime to Timestamp
Timestamp timestamp = new Timestamp(localDateTime.toDateTime().getMillis());
But if You still want to convert Timestamp into java.sql.Date then use this
java.sql.Date date = new java.sql.Date(timeStamp.getTime());