I am doing jdbc and calling a procedure with date parameter but my db tables date format is in dd-MMM-yy format hence i converted my string date into dd-MMM-yy format but I am unable to setDate(1,sdt) cuz sdt must be in java.sql.Date type and java.sql.Date format is yyyy-MM-dd hence I need help
My procedure is defined thus:
PROCEDURE pStoreData(d_sumDttm IN DATE, i_Retval out number);
Short Code:
System.out.print("Enter report date:");
String sdate = scanner.nextLine();
final Date date = new Date();
final SimpleDateFormat format = new SimpleDateFormat();
format.applyPattern(dd-MMM-yy);
final String sysdt = format.format(date);
java.sql.Date sqldt = java.sql.Date.valueOf(sysdt);
callablestate = connection.prepareCall("{call Report.pStoreDate(?,?)}");
callablestate.setDate(1,sqldt);
callablestate.registerOutParameter(2,Types.REF_CURSOR);
callable.execute();
Update
Posting this update since OP seems to be struggling with how to use the original solution.
Dear OP,
Java instantiates date/time/date-time in just one way and then you can format it in your custom way. The database works the same way. So, it doesn't matter what format you display to the user or in what format the user enters the date; once you parse it into date/time/date-time object by applying the corresponding format, you just pass it to Java/DB and Java/DB will take care of the rest.
import java.time.LocalDate;
import java.util.Scanner;
import com.mysql.jdbc.CallableStatement;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter report date in MM-dd-yyyy format: ");
String strDate = scanner.nextLine();
LocalDate localDate = LocalDate.parse(strDate, DateTimeFormatter.ofPattern("MM-dd-yyyy"));
CallableStatement st = conn.prepareCall("{call Report.pStoreDate(?,?)}");
st.setObject(1, localDate);
st.registerOutParameter(2, Types.REF_CURSOR);
st.execute();
}
}
Original answer:
I suggest you do not use the outdated and error-prone java.util.Date. Use LocalDate instead as shown below:
LocalDate localDate = LocalDate.now();
PreparedStatement st = conn.prepareStatement("INSERT INTO mytable (columnfoo) VALUES (?)");
st.setObject(1, localDate);
st.executeUpdate();
Related
public void setEmployeeDetails(String month,String year,String day) throws
SQLException, ParseException
{
String sql="INSERT INTO EmployeeDetails (SiteName,EmployeeName,EmployeePhoneNumber,Date) VALUES(?,?,?,?)";
pStmt = conn.prepareStatement(sql) ;
String date=month+"/"+day+"/"+year;
SimpleDateFormat format = new SimpleDateFormat("MM/dd/yyyy");
java.util.Date parsed = format.parse(date);
java.sql.Date sql_date = new java.sql.Date(parsed.getTime());
System.out.println(sql_date);
}
public static void main(String args[]) throws SQLException, ClassNotFoundException, ParseException{
Employee_Details_DAO e=new Employee_Details_DAO();
e.setEmployeeDetails("12","2006","10");
}
I want to convert string date as format MM/ddd/yyy to sql ms access date format. But I got the output as 2006-12-10 but output should be as 12/10/2006
If System.out.println(sql_date); is displaying the date value as 2006-12-10 it is because it is using a default yyyy-mm-dd format, either from Java or from the operating system. It doesn't mean that the date is "wrong", it is just being displayed in a different way.
Always remember:
Date values do NOT have formats. They are just (numeric) values that correspond to a particular date.
[String] Representations of Dates do have a format. However, the format does not affect the value in any way. Whether it's 2006-12-25 or 12/25/2006 or December 25, 2006 or 2006 décembre 25 the Date value is still the same.
So, you don't need to worry about using any particular format for a Date parameter, just pass the value itself:
try (
Connection conn = DriverManager.getConnection(connStr);
PreparedStatement ps = conn.prepareStatement(
"INSERT INTO EmployeeDetails ([Date]) VALUES (?)")) {
String month = "12"; //
String year = "2006"; // sample data
String day = "10"; //
ps.setDate(1, java.sql.Date.valueOf(year + "-" + month + "-" + day));
ps.executeUpdate();
}
System.out.println(format.format(sql_date));//12/10/2006
java.sql.Date is a sub-class of java.util.Date. So we can format for java.sql.Date same as java.util.Date.
I want to convert java.util.Date to java.sql.Date but I want hours, minutes, and seconds as well but java.sql.Date can be used only to store date(no time) . I tried the below code but it is giving only year, month, and day for the java.sql.Date object.
SimpleDateFormat format = new SimpleDateFormat("yyyyMMddHHmmss");
Date parsed = format.parse("20110210120534");
System.out.println(format.parse("20110210120534"));
java.sql.Date sql = new java.sql.Date(parsed.getTime());
System.out.println("SQL date is= "+sql);
Current output:
2011-02-10
Desired output:
2011-02-10 12:05:34
The java.sql.Date type is used to store only date (no time) information, as it maps to the SQL DATE type, which doesn't store time. What its toString() method does is:
Formats a date in the date escape format yyyy-mm-dd.
To achieve the desired output you can use java.sql.Timestamp, which stores date and time information, mapping to the SQL TIMESTAMP type. Its toString() method outputs what you need:
Formats a timestamp in JDBC timestamp escape format: yyyy-mm-dd hh:mm:ss.fffffffff, where ffffffffff indicates nanoseconds.
Example:
java.text.DateFormat format = new java.text.SimpleDateFormat("yyyyMMddHHmmss");
java.util.Date date = format.parse("20110210120534");
java.sql.Timestamp timestamp = new java.sql.Timestamp(date.getTime());
System.out.println(timestamp); // prints "2011-02-10 12:05:34.0"
As other folks said, you need to use java.sql.TimeStamp.
public class Test {
public static void main(String[] args) {
java.util.Date date = new java.util.Date();
java.sql.Timestamp sqlTimeStamp = new java.sql.Timestamp(date.getTime());
System.out.println("util-date:" + date);
System.out.println("sql-timestamp:" + sqlTimeStamp );
}
}
http://tutorials.jenkov.com/java-date-time/java-sql-date.html
I have jsp code that get date from the user (using html form) and I try to use the date in preparedStatament (sql).
the user enter date in format dd/mm/yyyy and i try to convert it into sql date yyyy-mm-dd...
this is the input type in the htl form:
<td><input type=date name="fdate"/></td>
<td><input type=date name="tdate"/></td>
this is the source code of dates.jsp (that run the sql):
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd");
String fDateStr = request.getParameter("fdate");
String tDateStr = request.getParameter("tdate");
Date fdate = format.parse(fDateStr);
Date tdate = format.parse(tDateStr);
PreparedStatement prSelect = con.prepareStatement("select show_id,date,artist, name from shows where date between ? and ?");
prSelect.setDate(1, fdate);
prSelect.setDate(2, tdate);
This is the error that i get from setDate line:
"The method setDate(int, java.sql.Date) in the type PreparedStatement is not applicable for the arguments (int, java.util.Date)"
How can I solve it?
SimpleDateFormat format = new SimpleDateFormat("yyyy-mm-dd"); should be like
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy",Locale.ENGLISH);
Try to use Locale for safety
Again Date fdate = format.parse(fDateStr); gives you java.util.Date you need to convert it o java.sql.Date to set it to PreparedStatement like this
public static Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null) {
Date sqlDate = new Date(date.getTime());
return sqlDate;
}
return null;
}
Then
prSelect.setDate(1, convertUtilDateToSqlDate(fdte));
prSelect.setDate(2, convertUtilDateToSqlDate(tdate));
You must use java.sql.Date instead of java.util.Date
Try this
prSelect.setDate(1, java.sql.Date.valueOf(fDateStr));
prSelect.setDate(2, java.sql.Date.valueOf(tDateStr));
This question already has answers here:
Converting ISO 8601-compliant String to java.util.Date
(31 answers)
Closed 8 years ago.
For example, I have this String: 06/10/2013 18:29:09. I want to convert this string and put it in a SQL database (as Date).
How can I convert this to an sql date, so that it could be inserted into a database? I want the hours minutes and seconds to remain as well.
I tried the following:
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
Date javaDate = sdf.parse("06/10/2013 18:29:09");
java.sql.Date date = new java.sql.Date(javaDate.getTime());
The problem is here:
java.sql.Date date = new java.sql.Date(javaDate.getTime());
java.sql.Date stores the date part of your timestamp. If you want/need to handle both date and time, use java.sql.Timestamp instead:
java.sql.Timestamp date = new java.sql.Timestamp (javaDate.getTime());
More info:
Date vs TimeStamp vs calendar?
You will use a SimpleDateFormat object to parse the string to java.util.date and then use the getTime() method to instantiate a java.sql.Date.
String input = "06/10/2013 18:29:09";
SimpleDateFormat sdf = new SimpleDateFormat("MM/dd/yyyy hh:mm:ss");
java.util.Date dt = sdf.parse(input);
java.sql.Date dtSql = new java.sql.Date(dt.getTime());
If you are working with String type for date input and then you want to save that in a database like MySQL, you should use an appropriate Date Format for it. There's a class called "SimpleDateFormat" which you can use for that purpose. You can find a sample in the following link, also a brief explanation on how it works. Hope it helps.
Example: http://www.java2s.com/Tutorial/Java/0040__Data-Type/SimpleDateFormat.htm
Best Regards.
Here's a simple demo. In a Database table like this.
You can insert into it like this.
//the SQL statement for creating the database table
create table user(id, integer primary key, username varchar(100), date_created varchar(100));
//the java code to insert into the table created above.
try{
String date = new SimpleDateFormat("dd/MM/YYYY HH:mm:ss").format(new Date());
String sql = "insert into user(username, date_created) values('olupotd', '"+date+"')";
int done = statement.executeUpdate(sql);
if(done > 0)
//inserted
else
//not inserted.
}catch(java.sql.SQLException e){}
Hope that helps
I have an Oracle Date type to which I need to insert the current date.
I am using Java to generate this date but everything I've tried so far yeilds the following error:
java.sql.SQLException: ORA-01843: not a valid month
Can anyone suggest java code to generate a proper date?
Update:
The dates in the DB look like 11-DEC-06
SO, I've tried the following:
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("d-MMM-yy");
String date = sdf.format(cal.getTime());
And this doesn't work
I would suggest instead of building a string query (which I am guessing you are doing), you instead use a PreparedStatement, which is generally easier (especially with things like this) as well as safer:
String rowToUpdate = "foo";
PreparedStatement ps = myConnection.prepareStatement(
"UPDATE my_table SET date_field=? WHERE id=?");
Calendar cal = Calendar.getInstance();
java.sql.Date sqlDate = new java.sql.Date(cal.getTime().getTime());
ps.setDate(1, sqlDate);
ps.setString(2, rowToUpdate);
int updated = ps.executeUpdate();
Use java.sql.Date or java.sql.Timestamp, depending on your requirements.
java.sql.Date sqlDate = new java.sql.Date(new java.util.Date().getTime());
If you are going to make the query using a String version of the date then you may need to add the Oracle to_date function. You could do it like this (notice the extra d in the SimpleDateFormat)
Calendar cal = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yy");
String date = sdf.format(cal.getTime());
Then in the query you would put
String query = "select * from table where date_column=to_date('" + date +"','dd-Mon-yy')";