问题
i want to insert null value into an DATETIME Field through PrepareStatement using JDBC (using Mysql Database) i have tried following ways but nothing is worked.
i have a method " Util.dateconvertdate " it use to convert input date into a formatted string type
public static String dateconvertdate(Timestamp timestamp) {
Date date=null;
String formattedDate="";
if(timestamp != null){
SimpleDateFormat sdf = new SimpleDateFormat("dd-MMM-yyyy hh:mm:ss");
SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
Date date1 = new java.util.Date(timestamp.getTime());
formattedDate = formatter.format(date1);
}
else return "NULL";
return formattedDate;
}
and i use to check whether it return null or date
if(Util.dateconvertdate(rs.getTimestamp("fld_dob")) !=null){
pmystmt.setString(17, (Util.dateconvertdate(rs.getTimestamp("fld_dob"))));
} else{
pmystmt.setNull(17, java.sql.Types.NULL);
}
and i tried with
pmystmt.setNull(17, java.sql.Types.DATE);
pmystmt.setNull(17, Types.NULL);
pmystmt.setInt(17, Types.NULL);
pmystmt.setString(17, "NULL");
pmystmt.setNull(17, Types.DATE);
pmystmt.setString(17, null);
pmystmt.setDate(17, null);
but nothing is working it is throwing exception like
com.mysql.jdbc.MysqlDataTruncation: Data truncation: Incorrect datetime value: 'NULL' for column 'dob' at row 1
at com.mysql.jdbc.MysqlIO.checkErrorPacket(MysqlIO.java:2936)
at com.mysql.jdbc.MysqlIO.sendCommand(MysqlIO.java:1601)
at com.mysql.jdbc.MysqlIO.sqlQueryDirect(MysqlIO.java:1710)
at com.mysql.jdbc.Connection.execSQL(Connection.java:2436)
at com.mysql.jdbc.PreparedStatement.executeInternal(PreparedStatement.java:1402)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1694)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1608)
at com.mysql.jdbc.PreparedStatement.executeUpdate(PreparedStatement.java:1593)
at com.members.App_users.AddRecords(App_users.java:66)
at com.main.Start.main(Start.java:47)
any help will be appreciated. Thanks
回答1:
If your table column is nullable then Try to use it. It may help you.
pmystmt.setNull(17, java.sql.Types.TIMESTAMP);
回答2:
In your database url include zeroDateTimeBehavior=convertToNull while setting datasource.
jdbc:mysql://ip_address:port/databasename?zeroDateTimeBehavior=convertToNull
来源:https://stackoverflow.com/questions/27957727/insert-null-for-datetime-field-through-preparestatement-using-jdbc