Insert java.sql.Timestamp in MySQL

1

When I try to insert an object Timestamp of Java in a column of type Timestamp in MySQL I receive the following error:

  

com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: '' for column '' fechhour 'at row 1

Why does this happen? I leave the code I am using below:

Database code:

CREATE DATABASE  IF NOT EXISTS 'prueba';
USE 'prueba';

DROP TABLE IF EXISTS 'moments';

CREATE TABLE 'moments' (
  'id' int(11) NOT NULL AUTO_INCREMENT,
  'fechhour' timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  PRIMARY KEY ('id')
) ENGINE=InnoDB AUTO_INCREMENT=4 DEFAULT CHARSET=utf8;

Code of the java applet to take the test:

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.Calendar;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JSpinner;

public class principal extends javax.swing.JFrame {

    Connection conSet;

    public principal() {
        initComponents();

        try {
            DriverManager.registerDriver(new com.mysql.jdbc.Driver());
        } catch (SQLException ex) {
            Logger.getLogger(principal.class.getName()).log(Level.SEVERE, null, ex);
        }
        String url = "jdbc:mysql://localhost/prueba";
        try{
            String url1 = System.getProperty("JDBC_URL");
            if (url1 != null)
                url = url1;
        }catch (Exception e){
            System.out.println("Seguridad ignorada");
        }
        try {
            conSet = DriverManager.getConnection(url, "root", "12345678");
        } catch (SQLException ex) {
            Logger.getLogger(principal.class.getName()).log(Level.SEVERE, null, ex);
        }



    }

    @SuppressWarnings("unchecked")

        private void initComponents() {una ventana y un boton}

    private void jButton1ActionPerformed(java.awt.event.ActionEvent evt) {                                         
        Timestamp hoy=getNow();
        Object[][] values=new Object[1][2];
        values[0][0]="fechhour";
        values[0][1]=hoy;
        System.out.println("la variable hoy es de la clase... "+hoy.getClass());
        try {
            insert("moments", values);
        } catch (SQLException ex) {
            Logger.getLogger(principal.class.getName()).log(Level.SEVERE, null, ex);
        }

    }                                        

    public static void main(String args[]) {

        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(principal.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }

        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new principal().setVisible(true);
            }
        });
    }

    private javax.swing.JButton jButton1;

    public void insert(String tableName, Object values[][]) throws SQLException{
        String cadCampos="(";
        String cadValues="(";
        for(int i=0; i<values.length; i++){
            cadCampos+=values[i][0];
            cadValues+="?";
            if(i!=values.length-1){
                cadCampos+=", ";
                cadValues+=", ";
            }
        }
        cadCampos+=")";
        cadValues+=")";
        PreparedStatement pstmt = conSet.prepareStatement ("insert into "+tableName+cadCampos+" values "+cadValues);
        for(int i=0; i<values.length; i++){
            System.out.println(values[i][0]+": "+values[i][1]);
            pstmt.setObject(i+1, values[i][1]);
        }
        System.out.println("insert into "+tableName+cadCampos+" values "+cadValues);
        pstmt.execute();
        pstmt = conSet.prepareStatement ("commit");
        pstmt.execute();
        pstmt.close();
    }

    public static java.sql.Timestamp getNow(){
        java.util.Calendar calendarHoy=Calendar.getInstance();
        java.util.Date hoy=calendarHoy.getTime();
        Timestamp hoySql=new Timestamp(hoy.getTime());
        System.out.println("Hoy es: "+hoySql);
        return hoySql;
    }

}

The code seems complex because it is copied from what generates NetBeans , but it is just a window with a button that when pressed puts the current date and time in a database with only one table of 2 columns: id and moment .

On the other hand, the function insert is created to pass a table [x] [2] with names of columns and values and the name of the table where to insert it. Maybe it is silly because there will be something already done to insert objects in MySQL, but I am new in this world of programming, and since I am going to perform that action in many different tables within my project I have thought of doing it that way. If someone knows how to do the same in a better way, I accept advice.

Thanks for everything.

    
asked by Ignacio 21.05.2017 в 23:46
source

0 answers