java.sql.ResultSet类的使用及代码示例

x33g5p2x  于2022-01-28 转载在 其他  
字(13.9k)|赞(0)|评价(0)|浏览(305)

本文整理了Java中java.sql.ResultSet类的一些代码示例,展示了ResultSet类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。ResultSet类的具体详情如下:
包路径:java.sql.ResultSet
类名称:ResultSet

ResultSet介绍

[英]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).
[中]表示数据库表项的对象接口,作为查询结果返回数据库。
结果集有一个指向当前数据表行的光标。创建结果集时,光标的位置位于第一行前面一个位置。要将光标移动到第一行和连续行,请使用下一种方法。只要结果集中有更多行,下一个方法就会返回true,否则返回false。
结果集的默认类型无法更新,其光标只能在数据行中向前移动。这意味着只能通读一次。但是,还实现了其他类型的ResultStar:可更新类型,以及光标可以在数据行中前后滚动的类型。下面的示例演示了如何创建这样的结果集:
连接con;语句aStatement=con。createStatement(ResultSet.CONCUR_可更新);ResultSet theResultSet=//theResultSet可滚动且可更新
ResultSet接口提供了一系列从当前行的列中检索数据的方法,例如getDate和getFloat。这些列可以通过它们的索引号(从1开始)或它们的名称进行检索——这两种列寻址技术都有不同的方法。列名不区分大小写。如果多个列具有相同的名称,那么getter方法将使用第一个匹配的列。这意味着,如果使用列名,则无法保证该名称将从预期的列检索数据——为确定起见,最好使用列索引。理想情况下,列应该从左到右读取,并且只读取一次,因为并非所有数据库都经过优化,可以处理其他读取数据的技术。
当通过适当的getter方法读取数据时,JDBC驱动程序将从数据库检索到的SQL数据映射到应用程序调用的方法所隐含的Java类型。JDBC规范有一个表,用于从SQL类型到Java类型的映射。
还有一些将数据写入结果集的方法,例如updateInt和updateString。update方法既可以用于修改现有行的数据,也可以用于在结果集中插入新的数据行。修改现有数据涉及将光标移动到需要修改的行,然后使用更新方法修改数据,然后调用ResultSet。更新方法。对于新行的插入,首先将光标移动到名为Insert row的特殊行,使用update方法添加数据,然后调用ResultSet。insertRow方法。
如果生成结果集的语句关闭、再次执行该语句或检索到同一语句的下一个结果集(如果该语句返回多个结果),则结果集将关闭。

代码示例

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;

相关文章

微信公众号

最新文章

更多

ResultSet类方法