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

How to Handle '0000-00-00 00:00:00' DATETIME Values in JDBC?

Susan Sarandon
Release: 2024-12-26 01:32:09
Original
923 people have browsed it

How to Handle '0000-00-00 00:00:00' DATETIME Values in JDBC?

Handling DATETIME Values '0000-00-00 00:00:00' in JDBC

The problematic '0000-00-00 00:00:00' DATETIME value, representing a quasi-null state, often triggers an exception when attempting to retrieve it as a string using ResultSet.getString(). To resolve this, consider the following options:

1. Casting to CHAR

To obtain the raw DATETIME string as it appears in the database, employ a MySQL-specific query:

SELECT CAST(add_date AS CHAR) AS add_date
Copy after login

2. JDBC URL Configuration

Alternatively, you can append zeroDateTimeBehavior=convertToNull to your JDBC URL:

jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull
Copy after login

This configures JDBC to convert '0000-00-00 00:00:00' values to NULL, allowing you to retrieve them without triggering an exception.

3. zeroDateTimeBehavior Configuration Property

For Connector/J versions 3.1 and above, the zeroDateTimeBehavior property offers more customization. By setting it to exception, convertToNull, or round, you can specify how DATETIME values are handled:

  • exception: Throws an SQL exception (default)
  • convertToNull: Returns NULL
  • round: Rounds the date to 0001-01-01

Refer to the MySQL manual for more details on this configuration property.

Note: In MySQL Connector/J 5.1.15, a bug affected the zeroDateTimeBehavior=convertToNull feature. Consult the official website's CHANGELOGS for updates on bug fixes.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template