数据库查询时如何检测结果集是否为空

fangzhaoguo 2011-10-02 01:35:02
数据库查询时如何检测结果集是否为空
try
{
con=DriverManager.getConnection("jdbc:MySQL://127.0.0.1:3306/Phone_Contacts", "root","fzg125009");
if(radio_name.isSelected())
{
pre=con.prepareStatement("SELECT DISTINCT * FROM Contact WHERE name Like '"+field_name.getText()+"%'");
}
else if(radio_phone.isSelected())
{
pre=con.prepareStatement("SELECT DISTINCT * FROM Contact WHERE mobile Like '"+field_phone.getText()+"%'");
}
rs=pre.executeQuery();
row=new CachedRowSetImpl();
row.populate(rs);
if(row.wasNull())//这个不能被执行,所以这样检测不可以
{
text.append("Sorry,无此记录!\n");
}
con.close();
while(row.next())
{
text.append(row.getString(1)+"\t");
text.append(row.getString(2)+"\n");
}
}
catch (SQLException error)
{
System.out.println("error!");
}

谢谢大家
...全文
324 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
fangzhaoguo 2011-10-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 baillluu 的回复:]

while(row.next())
{
text.append(row.getString(1)+"\t");
text.append(row.getString(2)+"\n");
}
row.close();
pre.close();
con.close();
if(text.toString().equals("")
{
……
[/Quote]

不过你的也很不错,谢谢
fangzhaoguo 2011-10-02
  • 打赏
  • 举报
回复
[Quote=引用 4 楼 baillluu 的回复:]

while(row.next())
{
text.append(row.getString(1)+"\t");
text.append(row.getString(2)+"\n");
}
row.close();
pre.close();
con.close();
if(text.toString().equals("")
{
……
[/Quote]
我有一个更好的方法

表示自己解决了

try
{
con=DriverManager.getConnection("jdbc:MySQL://127.0.0.1:3306/Phone_Contacts", "root","00000");
if(radio_name.isSelected())
{
pre=con.prepareStatement("SELECT DISTINCT * FROM Contact WHERE name Like '"+field_name.getText()+"%'");
}
else if(radio_phone.isSelected())
{
pre=con.prepareStatement("SELECT DISTINCT * FROM Contact WHERE mobile Like '"+field_phone.getText()+"%'");
}
rs=pre.executeQuery();
row=new CachedRowSetImpl();
row.populate(rs);
con.close();
if(!row.next())//这儿
{
text.append("Sorry,无此记录!\n");
}
else
{
row.beforeFirst();
while(row.next())
{
text.append(row.getString(1)+"\t");
text.append(row.getString(2)+"\n");
}
}
}
catch (SQLException error)
{
System.out.println("error!");
}
baillluu 2011-10-02
  • 打赏
  • 举报
回复
while(row.next())
{
text.append(row.getString(1)+"\t");
text.append(row.getString(2)+"\n");
}
row.close();
pre.close();
con.close();
if(text.toString().equals("")
{
text.append("Sorry,无此记录!\n");

}
fangzhaoguo 2011-10-02
  • 打赏
  • 举报
回复
[Quote=引用 1 楼 ioe_gaoyong 的回复:]

检测结果为空可以这样判断
if(rs==null){
System.out.println("查询结果为空");
text.append("Sorry,无此记录!\n");
}
[/Quote]
试了一下,不可以
fangzhaoguo 2011-10-02
  • 打赏
  • 举报
回复
能这样用吗??
我没试过
不过字符串比较中这个都不可用==的
风尘中国 2011-10-02
  • 打赏
  • 举报
回复
检测结果为空可以这样判断
if(rs==null){
System.out.println("查询结果为空");
text.append("Sorry,无此记录!\n");
}

62,614

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧