java 空值处理,在JAVA中处理结果集中的null值

本文探讨如何在Java中处理ResultSet中的null值,避免因查询结果中某列可能为null而导致的NullPointerException。通过示例说明如何使用wasNull()方法判断并设置空字符串,同时提供解决循环遍历中处理空值的完整代码段。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

I currently have a resultset returned and in one of the columns the string value may be null (i mean no values at all). I have a condition to implement like following

rs = st.executeQuery(selectSQL);

output = rs.getString("column");

Since the column may be null in the database, the rs.getString() will throw a NullPointerException() when column is null. If column is null, I want output to be an empty string like output = ""; I can't check if(rs.getString("column) != null either. How can I tackle this situation?

My real problem:

try{

rs = st.executeQuery(sql);

int i = 0;

while(rs.next()){

output[i] = rs.getString(column);

// column field in the database contains multiple results, but sometimes

// may be null

i++;

}

}catch{SQLException e){

e.printStackTrace();

// other than tracing the exception i want to fill the array too

}

return output;

Now if one of the column values contains no value i.e. null i want output[i] defined as N/A. All this problem stems from the fact that the column field is NULL allowed in the database. And sorry guys for telling you that its a NPE while in fact its SQLException...(noob here).

解决方案

Since the column may be null in the

database, the rs.getString() will

throw a NullPointerException()

No.

rs.getString will not throw NullPointer if the column is present in the selected result set (SELECT query columns)

For a particular record if value for the 'comumn is null in db, you must do something like this -

String myValue = rs.getString("myColumn");

if (rs.wasNull()) {

myValue = ""; // set it to empty string as you desire.

}

You may want to refer to wasNull() documentation -

From java.sql.ResultSet

boolean wasNull() throws SQLException;

* Reports whether

* the last column read had a value of SQL NULL.

* Note that you must first call one of the getter methods

* on a column to try to read its value and then call

* the method wasNull to see if the value read was

* SQL NULL.

*

* @return true if the last column value read was SQL

* NULL and false otherwise

* @exception SQLException if a database access error occurs or this method is

* called on a closed result set

*/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值