R
R
Romario212018-05-28 14:42:05
Java
Romario21, 2018-05-28 14:42:05

JAVA JDBC unable to get single record from table?

Hello everyone, if the query returns several records, then everything is fine, but if one record is returned, then it is impossible to get it. Tell me what's the problem?

Statement stmt = dbConnent.getCon().createStatement();
                
                //Возвращает одну запись (CA3896D8-46C9-49EA-A94B-7E5B3CE8721C,belov_aa)
                String sql = "SELECT TOP(1) Id AS UID,Name AS NAME FROM SysAdminUnit WHERE Name='belov_aa'";
                
                System.out.println(sql);
                ResultSet rs = stmt.executeQuery(sql);
                while (rs.next()) {
                    String name = rs.getString("NAME");
                    String uid = rs.getString("UID");
                    System.out.println(uid+":"+name);
                }

If we remove the while, we get com.microsoft.sqlserver.jdbc.SQLServerException: The result set has no current row.,

Answer the question

In order to leave comments, you need to log in

3 answer(s)
N
netrox, 2018-05-28
@netrox

Try:

if (rs.next()) 
{
           String name = rs.getString("NAME");
           String uid = rs.getString("UID");
           System.out.println(uid+":"+name);
}

N
Neonoviiwolf, 2018-05-28
@Neonoviiwolf

In such cases, I write something like this

if (rs.next()) 
{
      do{
................................
      } while (rs.next());
}

so there is a cycle and you don’t need to sculpt it separately to issue one line

M
MaxLich, 2018-05-29
@MaxLich

If you are really trying to get the result without calling the next() method, then you will not succeed. The internal ResultSet pointer first comes before the first row . So in any case, next() needs to be called.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question