【问题标题】:Reading null values from ResultSet从 ResultSet 中读取空值
【发布时间】:2013-06-06 10:38:45
【问题描述】:

下表可能包含 STA、ETA 或 ATA 的空值:

CREATE TABLE `flightschedule` (
  `id` smallint(6) NOT NULL AUTO_INCREMENT,
  `flightNum_arr` varchar(40) DEFAULT NULL,
  `from_ICAO` varchar(20) DEFAULT NULL,
  `STA` datetime DEFAULT NULL,
  `ETA` datetime DEFAULT NULL,
  `ATA` datetime DEFAULT NULL,
  `pk_arr` varchar(10) DEFAULT NULL
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=5611 DEFAULT CHARSET=latin1;

查询是:

SELECT flightNum_arr,STA,ETA,ATA,airlineICAO,aircraftType,pk_arr FROM 航班时刻表”;

当我尝试在我的 Java 代码中从该表中读取数据时,出现以下错误:

java.sql.SQLException:无法将值“0000-00-00 00:00:00”从 第 2 列到 TIMESTAMP。

它发生在record[i] = rs.getString(i + 1);

我介绍了以下检查,但它似乎不起作用:

if(record[i] == null)
{
   record[i]= "";
}

代码:

public void setQuery(String query) {
        cache = new Vector();
        try {
          // Execute the query and store the result set and its metadata
          Connection con = getConnection();
          Statement statement = con.createStatement();
          ResultSet rs = statement.executeQuery(query);
          ResultSetMetaData meta = rs.getMetaData();
          colCount = meta.getColumnCount();
          // Rebuild the headers array with the new column names
          headers = new String[colCount];
          for (int h = 1; h <= colCount; h++) {
            headers[h - 1] = meta.getColumnName(h);
          }
          while (rs.next()) {
            String[] record = new String[colCount];
            for (int i = 0; i < colCount; i++) {
              record[i] = rs.getString(i + 1);
              if(record[i] == null)
              {
                  record[i]= "";
              }
            }
            cache.addElement(record);
          }
          fireTableChanged(null);         
          rs.close();
          if (con.getAutoCommit() != false) {
            con.close();
          }         
        } catch (Exception e) {
          cache = new Vector(); // blank it out and keep going.
          e.printStackTrace();
        }
      }

【问题讨论】:

  • 请提供整个堆栈跟踪。异常发生在上面的哪一行代码?您的查询是否包含使用时间戳列之一的 WHERE 子句?
  • @John B:请查看更新后的帖子。

标签: java sql datetime null resultset


【解决方案1】:

我认为问题在于您需要根据以下帖子配置连接以将零日期时间转换为 null:

handling DATETIME values 0000-00-00 00:00:00 in JDBC

【讨论】:

  • 谢谢。我介绍了这个 jdbc:mysql://yourserver:3306/yourdatabase?zeroDateTimeBehavior=convertToNull。现在它就像一个魅力!!!
【解决方案2】:

您应该使用 rs.getTimeStamp() 或 rs.getDate() 而不是 rs.getString 来表示 DateTimeColum

【讨论】:

    猜你喜欢
    • 2010-11-09
    • 2013-03-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    • 2016-08-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多