Java: creating a date object from a string and inserting into MySQL - java

Anytime I have to handle dates/times in java it makes me sad
I'm trying to parse a string and turn it into a date object to insert in a preparepared statement. I've been trying to get this working but am having no luck. I also get the helpful error message when I go to compile the class.
"Exception in thread "main" java.lang.Error: Unresolved compilation problem:
The method setDate(int, Date) in the type PreparedStatement is not applicable for the arguments (int, Date)"
Eh WTF?
Here is the offending code.
for(int i = 0; i < flights.size(); i++){
String[] details = flight[i].toString().split(":");
DateFormat formatter ;
formatter = new SimpleDateFormat("ddMMyyyy");
Date date = formatter.parse(details[1]);
PreparedStatement pstmt = conn.prepareStatement(insertsql);
pstmt.setString(1, details[0]);
pstmt.setDate(2, date);
pstmt.setString(3, details[2] + "00");
pstmt.setString(4, details[3]);
pstmt.setString(5, details[4]);
pstmt.setString(6, details[5]);
pstmt.setString(7, details[6]);
pstmt.setString(8, details[7]);
pstmt.setString(9, details[8]);
pstmt.executeUpdate();
}

PreparedStatement.setDate takes a java.sql.Date, not a java.util.Date.
(Out of interest, how come you're not actually seeing this as a compile-time error? Your life will become a lot easier if you can resolve compilation failures without having to get to that point in a test run...)

My guess is that you mixed java.util.Date and java.sql.Date ...

String to MySQL Date/Time
import java.sql.Date;
import java.sql.Time;
statement.setDate(4, Date.valueOf("2009-08-26"));
statement.setTime(5, Time.valueOf("12:04:08"));

Related

How to insert into JDate chooser value into db

I have a JDateChooser in my form. and I need to insert it's Date value into DB.
I used this method just after "public class Nonacademic extends javax.swing.JInternalFrame {" ,
and the method I used is mentioned below,
public static java.sql.Date convertUtilDateToSqlDate(java.util.Date date){
if(date != null) {
java.sql.Date sqlDate = new java.sql.Date(date.getTime());
return sqlDate;
}
JOptionPane.showMessageDialog(null, "No Dates are Specified!");
return null;
}
and In my Add button's actionPerformed event I used
Connection c=DBconnect.connect();
Statement s = (Statement) c.createStatement();
PreparedStatement statement = c.prepareStatement("INSERT into nonacademic ( empId, name, Dob, JoinedDate) VALUES (?,?,?,?)");
statement.setString(1,txtEmpId.getText());
statement.setString(2, txtNmae.getText());
statement.setDate(3,convertUtilDateToSqlDate( (Date) jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate( (Date) jDateChooserDateOfJoined.getDate()));
statement.executeUpdate();
Problem is It is gives this error,
java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date
When I search for a solution to this, I found that this runtime error happens due to Parent class Instance is casting into child class.So can u give me a suggestion to correct this code.
Note:
After done coding above code when I select a Date in JDateChooser It appears as this 2015-08-06, Before code above stuff It appears as Aug 6,2015.
Try below statements,
statement.setDate(3,convertUtilDateToSqlDate(jDateChooserDOB.getDate()));
statement.setDate(4, convertUtilDateToSqlDate(jDateChooserDateOfJoined.getDate()));
Reason:
This is because of import statements. You might have imported only java.sql.Date or java.sql.* statement in your code. All "Date" class you mentioned in your program will be treated as java.sql.Date. So JVM is trying to converting java.util.Date to java.sql.Date in those statement and throwing exception.

How can i insert value in timestamp datatype column in SQL using java or JSP

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()));

java sql - insert timestamp into sql database

I'm trying to insert a timestamp into a database, but my code throws an exception, which tells me it's something with my sql statement.
The exception message shown is:
"Fout in Rit_ToevoegenController.okKnop(): SQLException in RitDB.voegRitToe() - statement"
okKnop is a different method that calls voegRitToe().
The type of the column called 'starttijd' is TIMESTAMP, and the DB Data type is DateTime.
i'm fairly certain that it's the timestamp that causes problems, because the other 2 are just a String and an int.
Any help with making it work would be greatly appreciated. I need to insert both the time and date into the database for comparing later.
public void voegRitToe(Rit r) throws DBException{
Timestamp starttijd = new Timestamp(System.currentTimeMillis());
//Date date = new Date(starttijd.getTime());
try(Connection conn = ConnectionManager.getConnection();){
try(PreparedStatement stmt = conn.prepareStatement("insert into rit(starttijd, lid_rijksregisternummer, fiets_registratienummer) values(?,?,?)");){
stmt.setTimestamp(1, starttijd);
stmt.setString(2, r.getLid().getRegisterNr());
stmt.setInt(3, r.getFiets().getRegisNr());
stmt.execute();
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - statement");
}
}
catch(SQLException sqlEx){
throw new DBException("SQLException in RitDB.voegRitToe() - verbinding");
}
}
TIMESTAMP and DATETIME serve different purposes; TIMESTAMP is for automatic time stamping.
java.util.Date starttijd = new java.util.Date(System.currentTimeMillis());
java.util.Date starttijd = new java.util.Date(); // Or this
I guess you came at Timestamp, as java.sql.Date wraps java.util.Date by setting the time part to zero!
If the database server's time is correct, one could also do:
... VALUES(NOW(), ?, ?)
By the way, java 8 introduces new date/time classes and "improve" upon the JDBC usage, if you have a java 8 compliant driver.

Searching between 2 date

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);

Inserting custom date and current time into Oracle database using string variables

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);

Categories

Resources