0

I need to convert a string to date to allow me insert information in mysql table:

I tried this:

System.out.println("Escribe la fecha de nacimiento de socio:");
//Traduction to english:        set the date of birthday //

String fechaSocio  = sc.next();

Date fecha = null;
try {
  fecha = new SimpleDateFormat("ddMMyyyy").parse(fechaSocio);
} catch (ParseException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

but It's converting like that: Thu Mar 21 00:00:00 CET 1996

I need to convert to this :

01-01-1987 or 01011987

public class SocioDao {
static ClaseConexion conexion = new ClaseConexion();

public void insertar(Socio misocio){

System.out.println(misocio.getDATA_NAIXEMENT());
System.out.println("..........................");


  try {

        Statement statuo = conexion.getConnection().createStatement();


        statuo.executeUpdate("insert into socis(CODI_SOCI,DNI,NOM,COGNOMS,"
                + "DATA_NAIXEMENT,ADRECA,POBLACIO,TELEFON) values ('"
                + misocio.getCODI_SOCI() + "','" + misocio.getDNI()
                + "',' " + misocio.getNOM() + "','" + misocio.getCOGNOMS()
                + "','" + misocio.getDATA_NAIXEMENT() + "','"
                + misocio.getADREÇA() + "','" + misocio.getPOBLACIO()
                + "','" + misocio.getTELEFON() + "')");

        statuo.close();
        conexion.desconectar();
        System.out.println("Socio añadido correctamente");

    } catch (Exception e) {
        System.out.println("No se puede añadir un nuevo socio");




    }

}

}

user3325719
  • 75
  • 4
  • 14

2 Answers2

4

It seems like you are trying to pass a Date as a String in your MySQL query.

Don't. Instead use the appropriate date setter method in the PreparedStatement class.

Remember, a Date doesn't have a format. A format is only for displaying a date.

Community
  • 1
  • 1
Sotirios Delimanolis
  • 274,122
  • 60
  • 696
  • 724
  • 1
    See [this other answer by BalusC](http://stackoverflow.com/a/7626080/642706) for an example of what this answer suggests. – Basil Bourque Mar 09 '14 at 06:12
0

Use mysql function if you are trying to insert date in database..

for example:

INSERT INTO test (sampledate) VALUES (CURDATE());
KhAn SaAb
  • 5,248
  • 5
  • 31
  • 52