简体   繁体   中英

Not retrieving the records from SQL Server

I am using the following code to access sql server database table record. I can confirm that the table columns are retrieved. But due to some reasons, it does not retrieve any row. Am I missing anything?

I am using remote server MS SQL Server.

try  {
    try {
        Class.forName("net.sourceforge.jtds.jdbc.Driver").newInstance();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    }
    try {
        Connection DbConn = DriverManager.getConnection("jdbc:jtds:sqlserver://ServerName/DBName;user=sa;password=password");
        Statement stmt = DbConn.createStatement();
        ResultSet reset = stmt.executeQuery("select * from tblUser");

        String str = reset.getString(1);
        DbConn.close();
    } catch (SQLException e) {
    }
} catch (Exception e) {
    e.printStackTrace();
}

You need to call ResultSet#next() to advance the cursor to the first record of the result set. From the Javadoc :

Moves the cursor froward one row from its current position. A ResultSet cursor is initially positioned before the first row; the first call to the method next makes the first row the current row; the second call makes the second row the current row, and so on.

So your code should look like this:

try {
    String cs = "jdbc:jtds:sqlserver://ServerName/DBName;user=sa;password=password";
    Connection DbConn = DriverManager.getConnection(cs);
    Statement stmt = DbConn.createStatement();
    ResultSet reset = stmt.executeQuery("select * from tblUser");

    while (reset.next()) { 
        String str = reset.getString(1);
        // do something with this record
    }
    DbConn.close();
} catch (SQLException e) {
    // handle exception here
}

The initial pointer is located before the first row, so if you want the first result like in your example, do:

if(reset.next()) {
  String s = r.getString(1);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM