Home >Database >Mysql Tutorial >How to Handle MySQL's 0000-00-00 00:00:00 DATETIME Values with JDBC?

How to Handle MySQL's 0000-00-00 00:00:00 DATETIME Values with JDBC?

Barbara Streisand
Barbara StreisandOriginal
2025-01-02 13:05:38660browse

How to Handle MySQL's 0000-00-00 00:00:00 DATETIME Values with JDBC?

JDBC Null Handling for DATETIME Values of 0000-00-00 00:00:00

MySQL treats DATETIME values of 0000-00-00 00:00:00 as "quasi-null" values, and attempting to retrieve such values as strings from a JDBC connection can result in an exception.

To handle this issue, consider using the following solutions:

Option 1: Casting to CHAR

You can explicitly cast the DATETIME column to CHAR in your SQL query:

SELECT CAST(add_date AS CHAR) AS add_date

This will return the raw DATETIME string without casting it to a specific data type.

Option 2: Using JDBC Configuration

Alternatively, you can configure your JDBC URL with the zeroDateTimeBehavior parameter:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull

With this configuration, DATETIME values of 0000-00-00 00:00:00 will be automatically converted to NULL in your ResultSet.

The zeroDateTimeBehavior parameter can take different values:

  • exception: Throws an exception (default)
  • convertToNull: Converts the value to NULL
  • round: Rounds the value to the nearest closest value (0001-01-01)

Note that this setting affects all DATETIME columns in your database.

Source:

  • MySQL Manual: https://dev.mysql.com/doc/connector-j/5.1/en/connector-j-reference-configuration-properties.html

The above is the detailed content of How to Handle MySQL's 0000-00-00 00:00:00 DATETIME Values with JDBC?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn