0

Good afternoon,

I'm trying to get a String from a JTextField. Then convert it to Date for afterwards sending that into a MYSQL statement.

        String nom = jTextField_Name.getText().toUpperCase();
        int temp = Integer.parseInt(jTextField_Temp.getText());
        String d = jTextField_Date.getText();
        System.out.println("Inputs taken");

        SimpleDateFormat format = new SimpleDateFormat("yyyy/MM/dd");
        Date parsed = (Date) format.parse(d);
        java.sql.Date sql = new java.sql.Date(parsed.getTime());
        System.out.println("Converted to proper Date for MYSQL");

        int retorn = db.insertTemperatura(nom, sql, temp);
        if (retorn == 1){
            jTextArea_Result.setText("S'ha inserit "+nom+" amb la seva temperatura correctament!");
        } else{
            jTextArea_Result.setText("-----Hi ha hagut un ERROR a l'hora d'inserir "+nom+" amb la seva temperatura.\nIntenta-ho de nou sisplau.");
        }
        } catch (ParseException ex) {
            Logger.getLogger(GUI.class.getName()).log(Level.SEVERE, null, ex);
        }

The thing is, that i'm not doing the conversion right, i've tried diferent ways and I always came up with that error:

run:
Llegides entrades
Exception in thread "AWT-EventQueue-0" java.lang.ClassCastException: java.util.Date cannot be cast to java.sql.Date

I've used other types of format but I don't know what I'm doing wrong.

Thanks in advance!

The method I call for that insertion into the DDBB is:

 public int insertTemperatura(String nom, Date data, int temperatura){
    try {
        Statement s = c.createStatement();
        String query = "INSERT INTO TaulaTemp VALUES ('"+nom+"',"+temperatura+","+data+")";

        int numRows = s.executeUpdate(query);
        if (numRows > 0){
            return 1;
        }
        return 0;
    } catch (SQLException ex) {
        Logger.getLogger(DDBB.class.getName()).log(Level.SEVERE, null, ex);
        return -1;
    }
}
neoSmith
  • 67
  • 10
  • You are using the wrong Date class. – Code-Apprentice Mar 03 '17 at 16:23
  • 1
    You can pass directly a java.util.Date to mySQL... is not necesary Parse it to java.sql.Date – Dazak Mar 03 '17 at 16:24
  • 1
    Possible duplicate of [How to convert java.util.Date to java.sql.Date?](http://stackoverflow.com/questions/530012/how-to-convert-java-util-date-to-java-sql-date) – f1sh Mar 03 '17 at 16:24
  • 2
    You can't simply cast a ``java.util.Date`` to a ``java.sql.Date``... – f1sh Mar 03 '17 at 16:25
  • 1
    You have not shown the important code, i.e. the definition of `insertTemperatura`. Please [edit] you post and include that code. – Jim Garrison Mar 03 '17 at 16:39
  • 2
    Do not build your SQL like that, use a `PreparedStatement` with placeholders instead. Your code is wide open to SQL-Injection attacks. – Jim Garrison Mar 03 '17 at 16:39
  • 1
    As @JimGarrison said... use a `PreparedStatement`... I updated my answer so you can see it. – Dazak Mar 03 '17 at 16:49

1 Answers1

1

You can pass directly a java.util.Date to mySQL... is not necessary Cast it to java.sql.Date

Just delete this line:

java.sql.Date sql = new java.sql.Date(parsed.getTime());

and pass in this line the variable casted

int retorn = db.insertTemperatura(nom, parsed, temp);

UPDATE:

You should use a preparedStatement clause instead of put all your query in a String, like this:

String query = "INSERT INTO TaulaTemp VALUES (?,?,?)";

PreparedStatement preparedStatement = dbConnection.prepareStatement(query);
preparedStatement.setString(1, nom);
preparedStatement.setDate(2, data);
preparedStatement.setInt(3, temperatura);
// execute insert SQL stetement
preparedStatement .executeUpdate();

Remember to use PreparedStatement add the necesary import statement:

import java.sql.PreparedStatement;
Dazak
  • 1,011
  • 2
  • 9
  • 17
  • Hello Dazak, thanks for the answer. I've just tried and it keeps me saying the same. Can it be an error from the input type I get from my method **insertTemperatura**? I've just updated the question with it's code, maybe it's there where I should change it :S – neoSmith Mar 03 '17 at 16:40
  • As @JimGarrison said... use a PreparedStatement... I update my answer so you can see it – Dazak Mar 03 '17 at 16:48
  • Now I've changed the code with the prepared statement but the error seems to be in the same part. As I've put system.out.prints, it seems that it's not passing the line: Date parsed = (Date) format.parse(d); – neoSmith Mar 03 '17 at 17:00