Java JDBC how to pass date in - java

How can I take the the date value from my html, then add it to the database.
I tried many ways but its not working. I keep getting back a NULL value in the database or an error message "java.text.dateformat.parse(unknown source)"
HTML:
Date Of Birth: <input type="date" name="dob">
JAVA:
String date = request.getParameter("dob");
Date dob1 = new SimpleDateFormat("MM/dd/yyyy"));
PreparedStatement createUser = connection.prepareStatement(
"INSERT into users (dob1)" +
" VALUES ( ?)");{
createUser.setDate(1, (java.sql.Date) dob1);
int newUser = createUser.executeUpdate();
}

String date = request.getParameter("dob");
Date dob1 = new SimpleDateFormat("MM/dd/yyyy"));
This second line is wrong. Change to
Date dob1 = new SimpleDateFormat("MM/dd/yyyy")).parse(date);
edit
By the comment you're using the wrong date format. Use it instead.
Date dob1 = new SimpleDateFormat("yyyy-MM-dd")).parse(date);

Related

How to fix NumberFormatException?

SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
String selectQueryForPatient = "SELECT registration_id, dob FROM patient_registration WHERE registration_id IN(SELECT max(registration_id)FROM patient_registration)";
String insertQuery = "INSERT INTO patient_master_info(patient_id) VALUES (?);";
String id = null;
String dob = null;
int generatedID = 0;
try {
pst = con.prepareStatement(selectQueryForPatient);
rs = pst.executeQuery();
while(rs.next()){
id = Integer.toString(rs.getInt(1));
dob = rs.getString(2);
System.out.println("Id : "+id+" "+"DOB: "+dob);
Date dt = sdf.parse(dob);
dob = sdf.format(dt);
String result = id.concat(dob);
generatedID = Integer.parseInt(result);
}
pst = con.prepareStatement(insertQuery);
pst.setInt(1, generatedID);
pst.execute();
} catch(Exception e) {
e.printStackTrace();
}
For input string: "12919851203" I got java.lang.NumberFormatExceptionexception. How do I fix it?
`
I don't know what you are trying to do, but your problem is that the result of appending a date to an integer value easily exceeds the integer range.
For example, let id be "30" and dob (as read from the database) be "20190123". The result of id.concat(dob) is "3020190123", which is larger than "2147483647", the maximum value for an int.
Your sample value 12919851203 is even much larger (almost 13 billion, while Integer.MAX_VALUE is about 2 billion).
If the value has to be sortable like numbers (where 2 < 10) then you could change the datatype to long or BigInteger.
If the sorting doesn't matter (i.e. it's OK that "2" is larger than "10") then you could even store result as String (into a VARCHAR column).
Or you could explain what problem you want to solve so that we could find a better way to solve the problem.
This answer is not about the number format exception but about the date format mistake you have made.
For the moment, you are parsing 1986-03-01 into the date 1985-12-03 because your String dob contains -. You need two distinct formaters to get your result:
SimpleDateFormat sdfIn = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat sdfOut = new SimpleDateFormat("yyyyMMdd");
String dob = "1985-03-01";
Date dt = sdfIn.parse(dob);
dob = sdfOut.format(dt);
System.out.println(dob);
19850301
Of course, one could argue about the need to parse into a Date just to get a "similar" String, if you are sure about your data being a date, you can just remove - using :
dob = dob.replaceAll("-", "");
Last thing, you should use java.time API.
String dob = "1985-03-01";
LocalDate date = LocalDate.parse(dob, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
dob = date.format(DateTimeFormatter.ofPattern("yyyyMMdd"));
System.out.println(date);
System.out.println(dob);

UpdateQuery doesn't execute. How to fix this code?

I want to get the date in DATE column and want to compare with the current date. if the date is less than current date then I want to SET the value of PERMISSION column allow. But my Query doesn't execute.
Which I have tried is given in my below code.
Date date1 = null;
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
//current date
Date date = new Date();
date1 = date;
CurrentDate.setText(date1.toString());
String UpdateQuery = null;
String Allow = "allow";
UpdateQuery = "UPDATE company SET permission = '"+Allow+"' WHERE date < ?";
pst = conn.prepareStatement(UpdateQuery);
SimpleDateFormat dateFormate = new SimpleDateFormat("yyyy-MM-dd");
String addDate = CurrentDate.getText();
pst.setString(2, addDate);
pst.executeUpdate();
System.out.println("Updated");
I want to get a value of permission table to SET to "allow" when the update query is executing;
pst.setString(2, addDate);
I think this should be changed to:
pst.setString(1, addDate);
because you only have one parameter in your prepared statement.
Also, when comparing dates, you need to enclose them in single quotes, so changing your UpdateQuery string to
"UPDATE company SET permission = '"+Allow+"' WHERE date < '?' ";
is also a necessary step.

How to insert the user entered value in jsp input type "time" to MYSQL database using JDBC

I have created a complaint registration form in JSP and in that there is an input field of type "time", also the time should not always be the current time hence I cannot use the CURRENTTIME() method of SQL.
Now while assigning it to the database I am getting HTTP Status 500 – Internal Server Error as "check the manual that corresponds to your MySQL server version for the right syntax to use near '.'20:20:00')' at line 1".
Here I have used the "setString()" method.
I have tried setTime() but that too is not working here, while setString() is working for the date value and date is properly being inserted in the DB.*/
Here is my jsp code for inserting the time in "test" table of "PCS" database .
<%# page import="java.sql.*" %>
String time=request.getParameter("time");
String url="jdbc:mysql://localhost:3306/pcs";
String uname="root";
String passw="publiccomplaint";
String query="insert into test values(?)";
Class.forName("com.mysql.jdbc.Driver");
Connection
con=DriverManager.getConnection(url,uname,passw);
PreparedStatement st=con.prepareStatement(query);
st.setString(1,time);
int count=st.executeUpdate();
st.close();
con.close();
What is the correct way in inserting the time into MYSQL DB from the input type="time" field of the form.?
You can try like this
String time = "15:30:18";
DateFormat sdf = new SimpleDateFormat("hh:mm:ss");
Date date = sdf.parse(time);
System.out.println("Time: " + sdf.format(date));
You should convert your date stored in string variable to java.util.date and then java.sql.date
String startDate="01-Feb-2013"; // Input String
SimpleDateFormat sdf1 = new SimpleDateFormat("dd-MM-yyyy"); // New Pattern
java.util.Date date = sdf1.parse(startDate); // Returns a Date format object with the pattern
java.sql.Date sqlStartDate = new java.sql.Date(date.getTime());
System.out.println(sqlStartDate); // Outputs : 2013-02-01
Then
preparedStatement.setDate(1,sqlStartDate);
You should convert the time string to a java.time.LocalTime and use setObject to pass that as the parameter:
String time = "20:20:00"; // sample data
st.setObject(1, java.time.LocalTime.parse(time));

How to convert Java String to Teradata DATE and Timestamp

My java code generates two Strings:
String myDate = "10/10/2013";
String myTimestamp = "2013-10-09 14:30:20";
I need to feed these values to a prepared statement, so that I could upload them using jdbc to Teradata
Here is what I tried :
String in = " INSERT INTO " + myTab + " VALUES (?,?) ";
PreparedStatement prst = null;
prst = connection.prepareStatement(in);
// add date
prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));
//add timestamp
prst.setDate(2, (Date) new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimestamp));
The above code compiles but does not work. I get an empty string error . How can I convert a String into Teradata types DATE, TIMESTAMP in order to add them to the prepared statement ?
You could use the java.sql.Date constructor that takes a long, by using Date#getTime() and changing from
prst.setDate(1, (Date) new SimpleDateFormat("MM/dd/yyyy").parse(myDate));
to something like
prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy")
.parse(myDate)).getTime());
and the other one
prst.setDate(2, new java.sql.Date(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss")
.parse(myTimestamp)).getTime());
Try this:
prst.setDate(1, new java.sql.Date(new SimpleDateFormat("MM/dd/yyyy").parse(myDate).getTime()));
This will convert your date then create a new sqlDate.
prst.setTimestamp(2, new java.sql.Timestamp(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(myTimeStamp).getTime());)
for the timestamp use setTimeStamp not setDate.

inerting timestamp into table

My database column datatype is timestamp. How do I insert the current date and time using a PreparedStatement or Statement?
I have tried this:
java.util.Date date = new java.util.Date();
System.out.println("Current Date : " + dateFormat.format(date));
pstmt.setDate(9, new java.sql.Timestamp(date.getTime()));
But the value inserted in the table is 1328847536746. This not right, i am using sqlite
There is a separate Timestamp value class in java.sql.
pstmt.setTimeStamp(9, new java.sql.Timestamp(date.getTime()));
The javadoc explains:
public class Timestamp
extends Date
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value.
Use setTimestamp().
pstmt.setTimestamp(9, Timestamp.valueOf("2002-03-13 11:10:15.01"));
This is the code I've used so far to get it done
Timestamp nextRunTimestamp = null;
if(endDate != null || !endDate.equalsIgnoreCase(""))
{
DateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
dateFormat.parse(endDate);
Calendar tempDate = dateFormat.getCalendar();
tempDate.set(Calendar.HOUR, nextRunTime.get(Calendar.HOUR));
tempDate.set(Calendar.MINUTE, nextRunTime.get(Calendar.MINUTE));
tempDate.set(Calendar.SECOND, nextRunTime.get(Calendar.SECOND));
tempDate.set(Calendar.MILLISECOND, nextRunTime.get(Calendar.MILLISECOND));
if(nextRunTime.before(tempDate) || nextRunTime.equals(tempDate))
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
}
else
{
nextRunTimestamp = new Timestamp(nextRunTime.getTimeInMillis());
}
statement.setTimestamp(2, nextRunTimestamp);
statement.setInt(3, result.getInt("id"));
statement.executeUpdate();
DateFormat df = new SimpleDateFormat(yyyy/MM/dd HH:mm:ss); // any Date format
System.out.println("Current Date : " + df.format(new Date()));
pstmt.setDate(9, to_timestamp(df.format(new Date()),'YYYY/MM/DD HH24:MI:SS'));
Here you can use TO_DATE('todayDate', 'YYYY/MM/DD HH24:MI:SS') or
TO_TIMESTAMP('todayDate', 'YYYY/MM/DD HH24:MI:SS')

Categories

Resources