Tabnine Logo
ResultSet
Code IndexAdd Tabnine to your IDE (free)

How to use
ResultSet
in
java.sql

Best Java code snippets using java.sql.ResultSet (Showing top 20 results out of 27,936)

Refine searchRefine arrow

  • Connection
  • PreparedStatement
  • Statement
  • DriverManager
  • SQLException
canonical example by Tabnine

public void runQuery(String url, String sql) {
  try (Connection connection = DriverManager.getConnection(url);
     PreparedStatement preparedStatement = connection.prepareStatement(sql)) {
    // ... add parameters to the SQL query using PreparedStatement methods:
    //     setInt, setString, etc.
    try (ResultSet resultSet = preparedStatement.executeQuery()) {
      while (resultSet.next()) {
        // ... do something with result set
      }
    }
  } catch (SQLException e) {
    // ... handle SQL exception
  }
}
origin: stackoverflow.com

public static void main(String[] args) throws Exception {
  Class.forName("org.sqlite.JDBC");
  Connection conn = DriverManager.getConnection("jdbc:sqlite:test.db");
  Statement stat = conn.createStatement();
  stat.executeUpdate("drop table if exists people;");
  stat.executeUpdate("create table people (name, occupation);");
  PreparedStatement prep = conn.prepareStatement(
    "insert into people values (?, ?);");
  prep.setString(1, "Gandhi");
  prep.setString(2, "politics");
  prep.addBatch();
  prep.setString(1, "Turing");
  prep.setString(2, "computers");
  prep.addBatch();
  conn.setAutoCommit(false);
  prep.executeBatch();
  conn.setAutoCommit(true);
  ResultSet rs = stat.executeQuery("select * from people;");
  while (rs.next()) {
    System.out.println("name = " + rs.getString("name"));
    System.out.println("job = " + rs.getString("occupation"));
  rs.close();
  conn.close();
origin: stackoverflow.com

 public List<User> getUser(int userId) {
  String sql = "SELECT id, username FROM users WHERE id = ?";
  List<User> users = new ArrayList<>();
  try (Connection con = DriverManager.getConnection(myConnectionURL);
     PreparedStatement ps = con.prepareStatement(sql);) {
    ps.setInt(1, userId);
    try (ResultSet rs = ps.executeQuery();) {
      while(rs.next()) {
        users.add(new User(rs.getInt("id"), rs.getString("name")));
      }
    }
  } catch (SQLException e) {
    e.printStackTrace();
  }
  return users;
}
origin: stackoverflow.com

 Connection connection = DriverManager.getConnection(JDBC_URL, JDBC_USERNAME, JDBC_PASSWORD);
PreparedStatement statement = connection.prepareStatement(JDBC_SELECT);
ResultSet rs = statement.executeQuery();
PrintStream out = System.out;

if (rs != null) {
  while (rs.next()) {
    ResultSetMetaData rsmd = rs.getMetaData();
    for (int i = 1; i <= rsmd.getColumnCount(); i++) {
      if (i > 1) {
      out.print(",");
      }

      int type = rsmd.getColumnType(i);
      if (type == Types.VARCHAR || type == Types.CHAR) {
        out.print(rs.getString(i));
      } else {
        out.print(rs.getLong(i));
      }
    }

    out.println();
  }
}
origin: iluwatar/java-design-patterns

private Customer createCustomer(ResultSet resultSet) throws SQLException {
 return new Customer(resultSet.getInt("ID"), 
   resultSet.getString("FNAME"), 
   resultSet.getString("LNAME"));
}
origin: spring-projects/spring-framework

@Override
@Nullable
public String getClobAsString(ResultSet rs, int columnIndex) throws SQLException {
  logger.debug("Returning CLOB as string");
  if (this.wrapAsLob) {
    Clob clob = rs.getClob(columnIndex);
    return clob.getSubString(1, (int) clob.length());
  }
  else {
    return rs.getString(columnIndex);
  }
}
origin: apache/incubator-shardingsphere

@Override
public Object getCalendarValue(final String columnLabel, final Class<?> type, final Calendar calendar) throws SQLException {
  if (Date.class == type) {
    return resultSet.getDate(columnLabel, calendar);
  }
  if (Time.class == type) {
    return resultSet.getTime(columnLabel, calendar);
  }
  if (Timestamp.class == type) {
    return resultSet.getTimestamp(columnLabel, calendar);
  }
  throw new SQLException(String.format("Unsupported type: %s", type));
}

origin: spring-projects/spring-framework

@Test
public void testCloseConnectionOnRequest() throws Exception {
  String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";
  given(this.resultSet.next()).willReturn(false);
  given(this.connection.createStatement()).willReturn(this.preparedStatement);
  RowCountCallbackHandler rcch = new RowCountCallbackHandler();
  this.template.query(sql, rcch);
  verify(this.resultSet).close();
  verify(this.preparedStatement).close();
  verify(this.connection).close();
}
origin: spring-projects/spring-framework

@Test
public void testOracleSequenceMaxValueIncrementer() throws SQLException {
  given(dataSource.getConnection()).willReturn(connection);
  given(connection.createStatement()).willReturn(statement);
  given(statement.executeQuery("select myseq.nextval from dual")).willReturn(resultSet);
  given(resultSet.next()).willReturn(true);
  given(resultSet.getLong(1)).willReturn(10L, 12L);
  OracleSequenceMaxValueIncrementer incrementer = new OracleSequenceMaxValueIncrementer();
  incrementer.setDataSource(dataSource);
  incrementer.setIncrementerName("myseq");
  incrementer.setPaddingLength(2);
  incrementer.afterPropertiesSet();
  assertEquals(10, incrementer.nextLongValue());
  assertEquals("12", incrementer.nextStringValue());
  verify(resultSet, times(2)).close();
  verify(statement, times(2)).close();
  verify(connection, times(2)).close();
}
origin: stackoverflow.com

 // assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
    "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
  System.out.println(rs.getString(1));
}
origin: spotbugs/spotbugs

@ExpectWarning("ODR_OPEN_DATABASE_RESOURCE")
public void isReported(String url, String username, String password) throws Exception {
  Connection connection = DriverManager.getConnection(url, username, password);
  PreparedStatement pstmt = connection.prepareStatement("SELECT count(1) from tab");
  ResultSet rs = pstmt.executeQuery();
  while (rs.next()) {
    System.out.println(rs.getString(1));
  }
}
origin: spring-projects/spring-framework

@Test
public void testQueryForObjectWithMapAndInteger() throws Exception {
  given(resultSet.getMetaData()).willReturn(resultSetMetaData);
  given(resultSet.next()).willReturn(true, false);
  given(resultSet.getInt(1)).willReturn(22);
  Map<String, Object> params = new HashMap<>();
  params.put("id", 3);
  Object o = template.queryForObject("SELECT AGE FROM CUSTMR WHERE ID = :id",
      params, Integer.class);
  assertTrue("Correct result type", o instanceof Integer);
  verify(connection).prepareStatement("SELECT AGE FROM CUSTMR WHERE ID = ?");
  verify(preparedStatement).setObject(1, 3);
}
origin: apache/ignite

/**
 * @throws Exception If failed.
 */
@Test
public void testSchemaInUrlAndInQuery() throws Exception {
  try(Connection conn = DriverManager.getConnection(URL + "/\"cache2\"")) {
    Statement stmt = conn.createStatement();
    stmt.execute("select t._key, t._val, v._val " +
      "from \"cache1\".Integer t join Integer v on t._key = v._key");
    ResultSet rs = stmt.getResultSet();
    while (rs.next()) {
      assertEquals(rs.getInt(2), rs.getInt(1) * 2);
      assertEquals(rs.getInt(3), rs.getInt(1) * 3);
    }
  }
}
origin: spring-projects/spring-framework

@Test
public void testStringQueryWithoutResults() throws SQLException {
  given(resultSet.next()).willReturn(false);
  StringQuery query = new StringQuery(dataSource, SELECT_FORENAME_EMPTY);
  String[] results = query.run();
  assertThat(results, is(equalTo(new String[0])));
  verify(connection).prepareStatement(SELECT_FORENAME_EMPTY);
  verify(resultSet).close();
  verify(preparedStatement).close();
  verify(connection).close();
}
origin: stackoverflow.com

DriverManager.registerDriver(new oracle.jdbc.OracleDriver());
final Connection c = DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:XE", "system", "manager");
String plsql = "" +
" declare " +  
" end;";
CallableStatement cs = c.prepareCall(plsql);
cs.setString(1, "12345");
cs.registerOutParameter(2, Types.VARCHAR);
cs.registerOutParameter(3, OracleTypes.CURSOR);
cs.execute();
while (cursorResultSet.next ())
  System.out.println (cursorResultSet.getInt(1) + " " + cursorResultSet.getString(2));
cs.close();
c.close();
origin: spring-projects/spring-framework

@Test
public void testQueryForObjectWithInteger() throws Exception {
  String sql = "SELECT AGE FROM CUSTMR WHERE ID = 3";
  given(this.resultSet.next()).willReturn(true, false);
  given(this.resultSet.getInt(1)).willReturn(22);
  assertEquals(Integer.valueOf(22), this.template.queryForObject(sql, Integer.class));
  verify(this.resultSet).close();
  verify(this.statement).close();
}
origin: prestodb/presto

  private static void assertConnectionSource(Connection connection, String expectedSource)
      throws SQLException
  {
    String queryId;
    try (Statement statement = connection.createStatement();
        ResultSet rs = statement.executeQuery("SELECT 123")) {
      queryId = rs.unwrap(PrestoResultSet.class).getQueryId();
    }

    try (PreparedStatement statement = connection.prepareStatement(
        "SELECT source FROM system.runtime.queries WHERE query_id = ?")) {
      statement.setString(1, queryId);
      try (ResultSet rs = statement.executeQuery()) {
        assertTrue(rs.next());
        assertThat(rs.getString("source")).isEqualTo(expectedSource);
        assertFalse(rs.next());
      }
    }
  }
}
origin: spring-projects/spring-framework

@Before
public void setUp() throws SQLException {
  given(connection.createStatement()).willReturn(statement);
  given(connection.prepareStatement(anyString())).willReturn(preparedStatement);
  given(statement.executeQuery(anyString())).willReturn(resultSet);
  given(preparedStatement.executeQuery()).willReturn(resultSet);
  given(resultSet.next()).willReturn(true, true, false);
  given(resultSet.getString(1)).willReturn("tb1", "tb2");
  given(resultSet.getInt(2)).willReturn(1, 2);
  template.setDataSource(new SingleConnectionDataSource(connection, false));
  template.setExceptionTranslator(new SQLStateSQLExceptionTranslator());
  template.afterPropertiesSet();
}
origin: Alluxio/alluxio

try (Connection con = DriverManager.getConnection(mHiveURL, mHiveUserName, mHiveUserPassword)) {
 try (PreparedStatement dropTablePS = con.prepareStatement(sql)) {
  dropTablePS.execute();
 try (PreparedStatement loadTablePS = con.prepareStatement(sql)) {
  loadTablePS.executeUpdate();
 try (PreparedStatement describeTablePS = con.prepareStatement(sql)) {
  describeTablePS.execute();
  reportWriter.println("Result should be \"You passed Hive test!\" ");
  reportWriter.println("Checker result is: ");
  while (resultSet.next()) {
   reportWriter.println(resultSet.getString(1) + resultSet.getString(2));
origin: spotbugs/spotbugs

String str = null;
try {
  conn = DriverManager.getConnection("", "", "");
  stmt = conn.prepareStatement(str);
  stmt.setString(1, "");
  rs = stmt.executeQuery();
  se.printStackTrace();
} finally {
  try {
    if (rs != null) {
      rs.close();
      rs = null;
    se.printStackTrace();
      stmt.close();
      stmt = null;
    se.printStackTrace();
      conn.close();
      conn = null;
java.sqlResultSet

Javadoc

An interface for an object which represents a database table entry, returned as the result of the query to the database.

ResultSets have a cursor which points to the current data table row. When the ResultSet is created, the cursor's location is one position ahead of the first row. To move the cursor to the first and consecutive rows, use the next method. The next method returns true as long as there are more rows in the ResultSet, otherwise it returns false.

The default type of ResultSet can not be updated and its cursor can only advance forward through the rows of data. This means that it is only possible to read through it once. However, other kinds of ResultSetare implemented: an updatable type and also types where the cursor can be scrolled forward and backward through the rows of data. How such a ResultSet is created is demonstrated in the following example:

    Connection con; Statement aStatement = con.createStatement( ResultSet.CONCUR_UPDATABLE ); ResultSet theResultSet = // theResultSet is both scrollable and updatable

The ResultSet interface provides a series of methods for retrieving data from columns in the current row, such as getDate and getFloat. The columns are retrieved either by their index number (starting at 1) or by their name - there are separate methods for both techniques of column addressing. The column names are case insensitive. If several columns have the same name, then the getter methods use the first matching column. This means that if column names are used, it is not possible to guarantee that the name will retrieve data from the intended column - for certainty it is better to use column indexes. Ideally the columns should be read left-to-right and read once only, since not all databases are optimized to handle other techniques of reading the data.

When reading data via the appropriate getter methods, the JDBC driver maps the SQL data retrieved from the database to the Java type implied by the method invoked by the application. The JDBC specification has a table for the mappings from SQL types to Java types.

There are also methods for writing data into the ResultSet, such as updateInt and updateString. The update methods can be used either to modify the data of an existing row or to insert new data rows into the ResultSet . Modification of existing data involves moving the cursor to the row which needs modification and then using the update methods to modify the data, followed by calling the ResultSet.updateRowmethod. For insertion of new rows, the cursor is first moved to a special row called the Insert Row, data is added using the update methods, followed by calling the ResultSet.insertRow method.

A ResultSet is closed if the statement which generated it closes, the statement is executed again, or the same statement's next ResultSetis retrieved (if the statement returned of multiple results).

Most used methods

  • next
    Shifts the cursor position down one row in this ResultSet object. Any input streams associated with
  • getString
    Gets the value of a column specified by column name, as a String.
  • getInt
    Gets the value of a column specified by column name, as an intvalue.
  • close
    Releases this ResultSet's database and JDBC resources. You are strongly advised to use this method r
  • getLong
    Gets the value of a column specified by column name, as a longvalue.
  • getMetaData
    Gets the metadata for this ResultSet. This defines the number, types and properties of the columns i
  • getObject
    Gets the value of a column specified by column name as a Java Object. The type of the Java object wi
  • getTimestamp
    Gets the value of a column specified by column name, as a java.sql.Timestamp value. The supplied Cal
  • getBoolean
    Gets the value of a column specified by column name, as a boolean.
  • wasNull
    Determines whether the last column read from this ResultSetcontained SQL NULL.
  • getDouble
    Gets the value of a column specified by column name as a doublevalue.
  • getBytes
    Gets the value of a column specified by column name as a byte array.
  • getDouble,
  • getBytes,
  • getDate,
  • getFloat,
  • getShort,
  • getBigDecimal,
  • getTime,
  • getBlob,
  • getBinaryStream,
  • getByte

Popular in Java

  • Reading from database using SQL prepared statement
  • getSupportFragmentManager (FragmentActivity)
  • getSystemService (Context)
  • onCreateOptionsMenu (Activity)
  • HttpServer (com.sun.net.httpserver)
    This class implements a simple HTTP server. A HttpServer is bound to an IP address and port number a
  • HttpURLConnection (java.net)
    An URLConnection for HTTP (RFC 2616 [http://tools.ietf.org/html/rfc2616]) used to send and receive d
  • DataSource (javax.sql)
    An interface for the creation of Connection objects which represent a connection to a database. This
  • IOUtils (org.apache.commons.io)
    General IO stream manipulation utilities. This class provides static utility methods for input/outpu
  • DateTimeFormat (org.joda.time.format)
    Factory that creates instances of DateTimeFormatter from patterns and styles. Datetime formatting i
  • Logger (org.slf4j)
    The org.slf4j.Logger interface is the main user entry point of SLF4J API. It is expected that loggin
  • From CI to AI: The AI layer in your organization
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now