javax.sql.DataSource.getConnection()方法的使用及代码示例

x33g5p2x  于2022-01-17 转载在 其他  
字(10.0k)|赞(0)|评价(0)|浏览(561)

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

DataSource.getConnection介绍

[英]Creates a connection to the database represented by this DataSource.
[中]创建与此数据源表示的数据库的连接。

代码示例

代码示例来源:origin: spring-projects/spring-framework

@Override
public void shutdown(DataSource dataSource, String databaseName) {
  Connection con = null;
  try {
    con = dataSource.getConnection();
    if (con != null) {
      con.createStatement().execute("SHUTDOWN");
    }
  }
  catch (SQLException ex) {
    logger.info("Could not shut down embedded database", ex);
  }
  finally {
    if (con != null) {
      try {
        con.close();
      }
      catch (Throwable ex) {
        logger.debug("Could not close JDBC Connection on shutdown", ex);
      }
    }
  }
}

代码示例来源:origin: elasticjob/elastic-job-lite

private String getOriginalTaskId(final String taskId) {
  String sql = String.format("SELECT original_task_id FROM %s WHERE task_id = '%s' and state='%s' LIMIT 1", TABLE_JOB_STATUS_TRACE_LOG, taskId, State.TASK_STAGING);
  String result = "";
  try (
      Connection conn = dataSource.getConnection();
      PreparedStatement preparedStatement = conn.prepareStatement(sql);
      ResultSet resultSet = preparedStatement.executeQuery()
  ) {
    if (resultSet.next()) {
      return resultSet.getString("original_task_id");
    }
  } catch (final SQLException ex) {
    // TODO 记录失败直接输出日志,未来可考虑配置化
    log.error(ex.getMessage());
  }
  return result;
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public void delete(String storeName) throws IOException {
 try (Connection connection = dataSource.getConnection();
   PreparedStatement deleteStatement = connection.prepareStatement(DELETE_JOB_STORE_SQL)) {
  deleteStatement.setString(1, storeName);
  deleteStatement.executeUpdate();
  connection.commit();
 } catch (SQLException e) {
  throw new IOException("failure deleting storeName " + storeName, e);
 }
}

代码示例来源:origin: apache/geode

public static void listTableData(String tableName) throws NamingException, SQLException {
 Context ctx = cache.getJNDIContext();
 DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
 String sql = "select * from " + tableName;
 Connection conn = ds.getConnection();
 Statement sm = conn.createStatement();
 ResultSet rs = sm.executeQuery(sql);
 while (rs.next()) {
  System.out.println("id " + rs.getString(1) + " name " + rs.getString(2));
 }
 rs.close();
 conn.close();
}

代码示例来源:origin: apache/geode

/**
 * This method is used to return number rows from the timestamped table created by createTable()
 * in CacheUtils class.
 */
public int getRows(String tableName) throws NamingException, SQLException {
 Context ctx = cache.getJNDIContext();
 DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
 String sql = "select * from " + tableName;
 Connection conn = ds.getConnection();
 Statement sm = conn.createStatement();
 ResultSet rs = sm.executeQuery(sql);
 int counter = 0;
 while (rs.next()) {
  counter++;
  // System.out.println("id "+rs.getString(1)+ " name "+rs.getString(2));
 }
 rs.close();
 conn.close();
 return counter;
}

代码示例来源:origin: looly/hutool

/**
 * 获得表的所有列名
 * 
 * @param ds 数据源
 * @param tableName 表名
 * @return 列数组
 * @throws DbRuntimeException SQL执行异常
 */
public static String[] getColumnNames(DataSource ds, String tableName) {
  List<String> columnNames = new ArrayList<String>();
  Connection conn = null;
  ResultSet rs = null;
  try {
    conn = ds.getConnection();
    final DatabaseMetaData metaData = conn.getMetaData();
    rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
    while (rs.next()) {
      columnNames.add(rs.getString("COLUMN_NAME"));
    }
    return columnNames.toArray(new String[columnNames.size()]);
  } catch (Exception e) {
    throw new DbRuntimeException("Get columns error!", e);
  } finally {
    DbUtil.close(rs, conn);
  }
}

代码示例来源:origin: voldemort/voldemort

@Override
public ClosableIterator<Pair<ByteArray, Versioned<byte[]>>> entries() {
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  String select = "select key_, version_, value_ from " + getName();
  try {
    conn = datasource.getConnection();
    stmt = conn.prepareStatement(select);
    rs = stmt.executeQuery();
    return new MysqlClosableIterator(conn, stmt, rs);
  } catch(SQLException e) {
    throw new PersistenceFailureException("Fix me!", e);
  }
}

代码示例来源:origin: yu199195/hmily

private int executeUpdate(final String sql, final Object... params) {
  Connection connection = null;
  PreparedStatement ps = null;
  try {
    connection = dataSource.getConnection();
    ps = connection.prepareStatement(sql);
    if (params != null) {
      for (int i = 0; i < params.length; i++) {
        ps.setObject(i + 1, convertDataTypeToDB(params[i]));
      }
    }
    return ps.executeUpdate();
  } catch (SQLException e) {
    LOGGER.error("executeUpdate-> " + e.getMessage());
    return FAIL_ROWS;
  } finally {
    close(connection, ps, null);
  }
}

代码示例来源:origin: deeplearning4j/nd4j

/**
   * Delete the given ndarray
   *
   * @param id the id of the ndarray to delete
   */
  @Override
  public void delete(String id) throws SQLException {
    Connection c = dataSource.getConnection();
    PreparedStatement p = c.prepareStatement(deleteStatement());
    p.setString(1, id);
    p.execute();

  }
}

代码示例来源:origin: elasticjob/elastic-job-lite

private int getEventCount(final String tableName, final Collection<String> tableFields, final Condition condition) {
  int result = 0;
  try (
      Connection conn = dataSource.getConnection();
      PreparedStatement preparedStatement = createCountPreparedStatement(conn, tableName, tableFields, condition);
      ResultSet resultSet = preparedStatement.executeQuery()
      ) {
    resultSet.next();
    result = resultSet.getInt(1);
  } catch (final SQLException ex) {
    // TODO 记录失败直接输出日志,未来可考虑配置化
    log.error("Fetch EventCount from DB error:", ex);
  }
  return result;
}

代码示例来源:origin: stagemonitor/stagemonitor

private void executePreparedStatement() throws SQLException {
  try (final Connection connection = dataSource.getConnection()) {
    final PreparedStatement preparedStatement = connection.prepareStatement("SELECT * from STAGEMONITOR");
    preparedStatement.execute();
    final ResultSet resultSet = preparedStatement.getResultSet();
    resultSet.next();
  }
}

代码示例来源:origin: voldemort/voldemort

public void executeQuery(DataSource datasource, String query) throws SQLException {
  Connection c = datasource.getConnection();
  PreparedStatement s = c.prepareStatement(query);
  s.execute();
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public boolean exists(String storeName, String tableName) throws IOException {
 try (Connection connection = dataSource.getConnection();
   PreparedStatement queryStatement = connection.prepareStatement(SELECT_JOB_STATE_EXISTS_SQL)) {
  int index = 0;
  queryStatement.setString(++index, storeName);
  queryStatement.setString(++index, tableName);
  try (ResultSet rs = queryStatement.executeQuery()) {
   if (rs.next()) {
    return true;
   } else {
    return false;
   }
  }
 } catch (SQLException e) {
  throw new IOException("Failure checking existence of storeName " + storeName + " tableName " + tableName, e);
 }
}

代码示例来源:origin: apache/incubator-gobblin

@Override
public void delete(String storeName, String tableName) throws IOException {
 try (Connection connection = dataSource.getConnection();
   PreparedStatement deleteStatement = connection.prepareStatement(DELETE_JOB_STATE_SQL)) {
  int index = 0;
  deleteStatement.setString(++index, storeName);
  deleteStatement.setString(++index, tableName);
  deleteStatement.executeUpdate();
  connection.commit();
 } catch (SQLException e) {
  throw new IOException("failure deleting storeName " + storeName + " tableName " + tableName, e);
 }
}

代码示例来源:origin: apache/rocketmq-externals

private void initPositionFromBinlogTail() throws SQLException {
  String sql = "SHOW MASTER STATUS";
  Connection conn = null;
  ResultSet rs = null;
  try {
    Connection connection = dataSource.getConnection();
    rs = connection.createStatement().executeQuery(sql);
    while (rs.next()) {
      binlogFilename = rs.getString("File");
      nextPosition = rs.getLong("Position");
    }
  } finally {
    if (conn != null) {
      conn.close();
    }
    if (rs != null) {
      rs.close();
    }
  }
}

代码示例来源:origin: apache/geode

/**
 * This method is used to delete all rows from the timestamped table created by createTable() in
 * CacheUtils class.
 */
public int deleteRows(String tableName) throws NamingException, SQLException {
 Context ctx = cache.getJNDIContext();
 DataSource da = (DataSource) ctx.lookup("java:/SimpleDataSource"); // doesn't req txn
 Connection conn = da.getConnection();
 Statement stmt = conn.createStatement();
 int rowsDeleted = 0; // assume that rows are always inserted in CacheUtils
 String sql = "";
 sql = "select * from " + tableName;
 ResultSet rs = stmt.executeQuery(sql);
 if (rs.next()) {
  sql = "delete from  " + tableName;
  rowsDeleted = stmt.executeUpdate(sql);
 }
 rs.close();
 stmt.close();
 conn.close();
 return rowsDeleted;
}

代码示例来源:origin: looly/hutool

/**
 * 获得表的所有列名
 * 
 * @param ds 数据源
 * @param tableName 表名
 * @return 列数组
 * @throws DbRuntimeException SQL执行异常
 */
public static String[] getColumnNames(DataSource ds, String tableName) {
  List<String> columnNames = new ArrayList<String>();
  Connection conn = null;
  ResultSet rs = null;
  try {
    conn = ds.getConnection();
    final DatabaseMetaData metaData = conn.getMetaData();
    rs = metaData.getColumns(conn.getCatalog(), null, tableName, null);
    while (rs.next()) {
      columnNames.add(rs.getString("COLUMN_NAME"));
    }
    return columnNames.toArray(new String[columnNames.size()]);
  } catch (Exception e) {
    throw new DbRuntimeException("Get columns error!", e);
  } finally {
    DbUtil.close(rs, conn);
  }
}

代码示例来源:origin: spring-projects/spring-framework

@Before
public void setUp() throws Exception {
  this.connection = mock(Connection.class);
  this.dataSource = mock(DataSource.class);
  this.preparedStatement = mock(PreparedStatement.class);
  this.resultSet = mock(ResultSet.class);
  given(this.dataSource.getConnection()).willReturn(this.connection);
  given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement);
  given(preparedStatement.executeQuery()).willReturn(resultSet);
}

代码示例来源:origin: apache/geode

public static void destroyTable(String tableName) throws NamingException, SQLException {
 Context ctx = cache.getJNDIContext();
 DataSource ds = (DataSource) ctx.lookup("java:/SimpleDataSource");
 Connection conn = ds.getConnection();
 // System.out.println (" trying to drop table: " + tableName);
 String sql = "drop table " + tableName;
 Statement sm = conn.createStatement();
 sm.execute(sql);
 conn.close();
}

代码示例来源:origin: apache/incubator-gobblin

try (Connection connection = dataSource.getConnection();
  PreparedStatement createStatement = connection.prepareStatement(createJobTable)) {
 createStatement.executeUpdate();
} catch (SQLException e) {
 throw new IOException("Failure creation table " + stateStoreTableName, e);

相关文章