I am having a textbox field in my jsp called "req_date". The user is selecting a date from a javascript calendar in the format of "DD-MON-YY" ex. "29-aug-2010".So, now I am stuck while trying to insert it in the DB.
I tried " String queryString = "INSERT INTO Charity (req_date) VALUES (?)", but it is not inserting. How do I solve tis out.
The req_date is type of date in the DB.
Can you please help
Date format depends upon Database you use.
For reference Date formats with Oracle.
so your query should look like :
String queryString = "INSERT INTO Charity (req_date) VALUES (to_date('29-aug-2010', 'dd-mon-yyyy'))"
This is just to answer your question. But I will prefer usage of PreparedStatement as also suggested in other answers.
Your code using PreparedStatement should look something like following: (NOTE: I have not tested this code )
String formatIn = "dd-MMM-yyyy";
SimpleDateFormat sdfi = new SimpleDateFormat(formatIn);
java.util.Date inDate = sdfi.parse("29-Aug-2010");
java.sql.Date sqlDate = new java.sql.Date(inDate.getTime());
PreparedStatement prest = con
.prepareStatement("INSERT INTO Charity (req_date) VALUES (?)");
prest.setDate(1, sqlDate);
int row = prest.executeUpdate();
Use a PreparedStatement and its setDate(..). Or use a timestamp (long).
It depends on your database, PostgreSQL does recognize this format:
SELECT CAST('29-aug-2010' AS date);
Result:
'2010-08-29'
In most cases, you'd better use the ISO-format yyyy-mm-dd.
Related
I have run into this weird Timestamp to Date Conversion issue in Oracle SQL.
Here is the SQL statement:
String INSERT_SQL = String.format("INSERT INTO AUDIT_TASK (%s, %s, %s, %s) VALUES (AUDIT_TASK_SEQ.nextval,?,?,?)",ID,CLASS_NAME,TASK_STEP_TIMESTAMP,OPERATOR);
java.util.Calendar utcCalendarInstance = Calendar.getInstance(TimeZone .getTimeZone("UTC"));
java.util.Calendar cal = Calendar.getInstance();
final PreparedStatement stmt = con.prepareStatement(INSERT_SQL);
stmt.setString(1, audit.getClassName().getValue());
// Save the timestamp in UTC
stmt.setTimestamp(2,new Timestamp(cal.getTimeInMillis()), utcCalendarInstance);
When I execute this statement, while most of the times the creation_date and task_step_timestamp dates are same, but sometimes I get the task_step_timestamp generated with some bogus dates- like '25-APR-0000' or '00-Jan-0001' etc.
ID | Creation_date | Task_step_timestamp
1 |27-APR-2018 17:58:53| 25-APR-0000 09:00:45
2 |27-APR-2018 18:06:25| 00-Jan-0001 09:18:25
The data type of task_step_timestamp column in Oracle DB is 'DATE'.
Can some one suggest the cause of this inconsistent conversion of timestamp to date?
I don't understand why you are using String#format here. Just use a regular insert which mentions explicit columns:
String INSERT_SQL = "INSERT INTO AUDIT_TASK (ID, ERROR_MESSAGE, TASK_STEP_TIMESTAMP, OPERATOR) ";
INSERT_SQL += "VALUES (AUDIT_TASK_SEQ.nextval, ?, ?, ?)";
PreparedStatement stmt = con.prepareStatement(INSERT_SQL);
Then bind your values:
stmt.setString(1, audit.getErrorMessage() != null ? audit.getErrorMessage().getValue() : null);
stmt.setTimestamp(2, new Timestamp(cal.getTimeInMillis()), utcCalendarInstance);
stmt.setString(3, audit.getClassName().getValue());
Note carefully that the placeholders, in order from left to right, are for the error message, task step timestamp, and operator. Your original code appears to be binding the parameters out of order. By using an insert statement which explicitly mentions the columns, you may avoid this problem.
Edit:
It also doesn't make sense to me why you are worrying about time zones for your timestamp. Just get the numbers of milliseconds since the epoch, and then let the database store that as UTC:
Timestamp timestamp = new Timestamp(System.currentTimeMillis());
stmt.setTimestamp(2, timestamp);
I made a software using the java language and MS SQL Server as the database. The problem am facing is that when I search for a date range using two dates, it's giving items which I have not requested.
For example, if I need items from 1st to 7th October, it includes items on the 11th, 12th, 13th, 14th, 15th, 16th, etc.
the date format am using MMM d,yyyy
I have used the following code
String val1 = ((JTextField)jdate1.getDateEditor().getUiComponent()).getText();
String val2 = ((JTextField)jdate2.getDateEditor().getUiComponent()).getText();
String sql = " select * from Report_details where Date between '"+val1+"' and '"+val2+"' ";
// conn is some Connection
PreparedStatement myStmt = conn.prepareStatement(sql);
ResultSet rs = myStmt.executeQuery();
if(rs.next()){
// do stuff
}
Do not trust user input.
String sql = "select * from Report_details where Date between ? and ?";
....
Date dt1 = new SimpleDateFormat("MMM d,yyyy").parse(val1);
// better yet, have your date picker return a Date object
....
myStmt.setDate(1, dt1);
....
should be the way to go (or setTime or setTimestamp, depending on your table definition)
NB: do not copy paste this, just a hint to get you off in the right direction.
I have tried to add value using preparedStatement.
----Some piece of Code----
`
String query = "INSERT INTO COMMENTS VALUES(?,?,?)";
PreparedStatement ps = con.prepareStatement(query);
ps.setString(1, email);
ps.setString(2, name);
ps.setTimestamp(3, now);
3rd column is timestamp type. But this is showing error.
It shows a whole list of packages needed to be imported. But when i import a package, it asks me to create a variable named 'now'.
Help me, how to fill timestamp field in database using java or JSP.
Thanks in advance
'now' needs to be of type java.sql.Timestamp
you can run a quick test by doing
ps.setTimestamp(3,getCurrentTimeStamp());
where getCurrentTimeStamp() is
public java.sql.Timestamp getCurrentTimeStamp() {
java.util.Date today = new java.util.Date();
return new java.sql.Timestamp(today.getTime());
}
To shorten HocusPocus correct answer even more, maybe
ps.setTimestamp(3, new java.sql.Timestamp(java.lang.System.currentTimeMillis()));
Have a problem search between 2 date
my sql statement in java
String sql ="Select * from Payment where Payment_Date between '"+date_1+"' and '"+date_2+"'";
It give me data type mismatch, I guess my problem occur in '"+date_1+"' and '"+date_2+"' ??
date_1 and date_2 I get from
Date date_1 = date1.getDate();
Date date_2 = date2.getDate();
Start using a PreparedStatement , it will prevent SQL injections . Read this SO Q&A for more.
You can do something like this :
String sql ="Select * from Payment where Payment_Date between ? and ? ";
PreparedStatement pstmt = conn.prepareStatement(query);
pstmt.setDate(1, date_1 );
pstmt.setDate(2, date_2 );
// date_1 and date_2 objects should be of type java.sql.Date
Make sure you set the correct parameter types in the setXXX() methods. Remember if the data type for Payment_Date is DATE and related types, you need to set java.sql.Date in the setDate() method. If the data type of column is TIMESTAMP, then use java.sql.Timestamp and setTimestamp() method.
Footnote :-
If you have a java.util.Date object with you , you can convert that to java.sql.Date as :
java.sql.Date sqlDateObject = new java.sql.Date(utilDateObject.getTime());
Package of Date class must be java.sql not java.util.
pstmt = conn.prepareStatement("Select * from Payment where Payment_Date between ? and ?");
pstmt.setDate(1, date_1);
pstmt.setDate(2, date_2);
So what I want to do is set a custom date along with the current time into the DATE type in the Oracle database.
I get the string from textField in the form of mm/dd/yyyy
String tdate = textDate.getText().trim();
To simplify the details lets just insert the DATE into a small table.
Calendar calendar = Calendar.getInstance();
int hour = calendar.get(Calendar.HOUR);
int minute = calendar.get(Calendar.MINUTE);
int second = calendar.get(Calendar.SECOND);
String current_time = hour+":"+minute+":"+second;
now we have tdate as the string of date and current_time as the current time.
to put into a database with table defined as :
create table transaction(
tranaction_num integer,
time_of_transaction DATE);
now in jdbc
PreparedStatement pStmt = Conn.prepareStatement("insert into transaction values(?,?));
pStmt.setString(1, "1");
pStmt.setString(2, "to_date( '"+tdate+" "+current_time+"','mm/dd/yyyy hh24:mi:ss')");
pStmt.executeUpdate();
This gives me an error as below
ORA-01858: a non-numeric character was found where a numeric was expected
I know I am doing something wrong but I have tried so many things to get this working. I don't mind getting the current time some other way as long as it is working
Any help would be appreciated
You should parse the date string before handing it over to the database and you should use setInt() for the first parameter instead of setString()
SimpleDateFormat parser = new SimpleDateFormat("MM/dd/yyyy HH:mm:ss");
Date date = parser.parse(tdate+" "+current_time);
String sqlStmt = "INSERT INTO transaction(tranaction_num, time_of_transaction) VALUES(?,?)";
PreparedStatement pStmt = Conn.prepareStatement(sqlStmt);
pStmt.setInt(1, 1);
pStmt.setDate(2, new java.sql.Date(date.getTime()));
pStmt.executeUpdate();
If you want to pass a string, you probably want something like
String sqlStmt = "insert into transaction values(?,to_date(?,'mm/dd/yyyy hh24:mi:ss'))"
PreparedStatement pStmt = Conn.prepareStatement(sqlStmt);
pStmt.setString(1, "1");
pStmt.setString(2, tdate+" "+current_time);
pStmt.executeUpdate();
From a good coding standpoint, however, you would be much better served doing a setInt for the first parameter and a setDate on the second parameter rather than passing everything as strings.
Instead of
pStmt.setString(1, "1");
Use:
pStmt.setInt(1, 1);