import java.net.URL;
import java.net.URLConnection;
import java.sql.*;
public class searchlink{
public static void main(String args[]) throws Exception {
//String link="http://hosted.ap.org";
Connection con=null;
Statement stmt=null;
Statement stmtR=null;
if(con==null){
SQLConnection.setURL("jdbc:sqlserver://192.168.2.53\\SQL2005;user=sa;password=365media;DatabaseName=LN_ADWEEK");
con=SQLConnection.getNewConnection();
stmt=con.createStatement();
stmtR=con.createStatement();
}
ResultSet rs;
rs=stmt.executeQuery("select url from urls where url='http://www.topix.com/rty/elyria-oh'");
while(rs.next()){
String mem=rs.getString(1);
System.out.println("Result is "+mem);}
}
}
Run Code Online (Sandbox Code Playgroud)
如果查询返回一行,上面的程序将打印输出.如果查询未返回任何内容,程序将停止而不打印任何内容.
而不是在没有打印任何东西的情况下停止它,我希望程序识别出查询没有返回任何内容并打印输出,如下所示"SQL查询执行后没有返回任何内容".
如何识别使用某些方法或变量来执行查询而不返回任何行?
Mat*_*nes 11
boolean hasRows = false;
while(rs.next()){
hasRows = true;
// do other stuff required.
}
if(!hasRows)
{
// do stuff when no rows present.
}
Run Code Online (Sandbox Code Playgroud)
- 要么 -
if(!rs.next())
{
// do stuff when no rows prsent.
}
else
{
do{
// do stuff required
}while(rs.next());
}
Run Code Online (Sandbox Code Playgroud)
请记住检查if(!rs.next())是否会将光标前进到结果集中.在获得值之前不要再次前进.
正常的JDBC习惯用法是将结果收集到类似的集合中List<Entity>.另一个正常的习惯用法是在try-with-resources语句中打开资源,以便正确地自动关闭.您的代码就是通过将这些资源保持打开来泄漏数据库资源.如果在短时间内重复运行,则DB将耗尽资源.
这是一个启动示例:
public List<Entity> list() throws SQLException {
List<Entity> entities = new ArrayList<Entity>();
try (
Connection connection = database.getConnection();
PreparedStatement statement = connection.prepareStatement("SELECT id, name, value FROM entity");
ResultSet resultSet = statement.executeQuery();
) {
while (resultSet.next()) {
Entity entity = new Entity();
entity.setId(resultSet.getLong("id"));
entity.setName(resultSet.getString("name"));
entity.setValue(resultSet.getInteger("value"));
entities.add(entity);
}
}
return entities;
}
Run Code Online (Sandbox Code Playgroud)
这样您就可以使用常用List方法来确定结果的状态:
List<Entity> entities = entityDAO.list();
if (entities.isEmpty()) {
// It is empty!
}
else if (entities.size() == 1) {
// It has only one row!
}
else {
// It has more than one row!
}
Run Code Online (Sandbox Code Playgroud)