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

How to use
DataSource
in
javax.sql

Best Java code snippets using javax.sql.DataSource (Showing top 20 results out of 12,564)

Refine searchRefine arrow

  • Connection
  • PreparedStatement
  • ResultSet
  • Statement
  • InitialContext
  • SQLException
origin: alibaba/druid

public List<MonitorApp> listApp(String domain) throws SQLException {
  List<MonitorApp> list = new ArrayList<MonitorApp>();
  String sql = "select id, domain, app from druid_app " //
         + " where domain = ?";
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  try {
    conn = dataSource.getConnection();
    stmt = conn.prepareStatement(sql);
    stmt.setString(1, domain);
    rs = stmt.executeQuery();
    if (rs.next()) {
      list.add(readApp(rs));
    }
    return list;
  } finally {
    JdbcUtils.close(rs);
    JdbcUtils.close(stmt);
    JdbcUtils.close(conn);
  }
}
origin: spring-projects/spring-framework

@Override
public void setLogWriter(PrintWriter out) throws SQLException {
  this.dataSource.setLogWriter(out);
}
origin: spring-projects/spring-framework

@Override
public PrintWriter getLogWriter() throws SQLException {
  return this.dataSource.getLogWriter();
}
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: spotbugs/spotbugs

int countAfter = 0;
InitialContext initialContext = new InitialContext(ht);
DataSource ds = (DataSource) initialContext.lookup("jdbc/EdecDataSourceNonXA");
Connection con = null;
PreparedStatement statement = null;
ResultSet rs = null;
try {
  con = ds.getConnection();
      .prepareStatement("select count(*) as rowcount from edec_deklarationen_mgt where dko_spediteur_dekl_nr like ? and dko_spediteur_nr = ? ");
  statement.setString(1, spediDeklNr);
  statement.setString(2, spediNr);
  rs = statement.executeQuery();
  rs.next();
  countBefore = rs.getInt("rowcount");
  rs.close();
      .prepareStatement("DELETE FROM edec_deklarationen_mgt where dko_spediteur_dekl_nr like ? and dko_spediteur_nr = ?");
      .prepareStatement("DELETE FROM edec_deklarationen WHERE dek_id IN (SELECT d.dek_id FROM edec_deklarationen d "
      e.printStackTrace();
      e.printStackTrace();
      e.printStackTrace();
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: 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: elasticjob/elastic-job-lite

private boolean insertJobExecutionEvent(final JobExecutionEvent jobExecutionEvent) {
  boolean result = false;
  String sql = "INSERT INTO `" + TABLE_JOB_EXECUTION_LOG + "` (`id`, `job_name`, `task_id`, `hostname`, `ip`, `sharding_item`, `execution_source`, `is_success`, `start_time`) "
      + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?);";
  try (
      Connection conn = dataSource.getConnection();
      PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
    preparedStatement.setString(1, jobExecutionEvent.getId());
    preparedStatement.setString(2, jobExecutionEvent.getJobName());
    preparedStatement.setString(3, jobExecutionEvent.getTaskId());
    preparedStatement.setString(4, jobExecutionEvent.getHostname());
    preparedStatement.setString(5, jobExecutionEvent.getIp());
    preparedStatement.setInt(6, jobExecutionEvent.getShardingItem());
    preparedStatement.setString(7, jobExecutionEvent.getSource().toString());
    preparedStatement.setBoolean(8, jobExecutionEvent.isSuccess());
    preparedStatement.setTimestamp(9, new Timestamp(jobExecutionEvent.getStartTime().getTime()));
    preparedStatement.execute();
    result = true;
  } catch (final SQLException ex) {
    if (!isDuplicateRecord(ex)) {
      // TODO 记录失败直接输出日志,未来可考虑配置化
      log.error(ex.getMessage());    
    }
  }
  return result;
}

origin: alibaba/druid

protected String getConstValueFromDb(String domain, String app, String type, Long hash) {
  String sql = "select value from druid_const where domain = ? AND app = ? and type = ? and hash = ?";
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  try {
    conn = dataSource.getConnection();
    stmt = conn.prepareStatement(sql);
    stmt.setString(1, domain);
    stmt.setString(2, app);
    stmt.setString(3, type);
    stmt.setLong(4, hash);
    rs = stmt.executeQuery();
    if (rs.next()) {
      return rs.getString(1);
    }
  } catch (SQLException ex) {
    LOG.error("save const error error", ex);
  } finally {
    JdbcUtils.close(rs);
    JdbcUtils.close(stmt);
    JdbcUtils.close(conn);
  }
  return null;
}
origin: alibaba/canal

ResultSet rs = null;
try {
  conn = ds.getConnection();
  stmt = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
  stmt.setFetchSize(Integer.MIN_VALUE);
  rs = stmt.executeQuery(sql);
  return fun.apply(rs);
} finally {
  if (rs != null) {
    try {
      rs.close();
    } catch (SQLException e) {
      logger.error(e.getMessage(), e);
      stmt.close();
    } catch (SQLException e) {
      logger.error(e.getMessage(), e);
      conn.close();
    } catch (SQLException e) {
      logger.error(e.getMessage(), e);
origin: spring-projects/spring-framework

try {
  if (this.useNewConnection) {
    con = getDataSource().getConnection();
    if (con.getAutoCommit()) {
      mustRestoreAutoCommit = true;
      con.setAutoCommit(false);
    con = DataSourceUtils.getConnection(getDataSource());
  stmt = con.createStatement();
  if (!this.useNewConnection) {
    DataSourceUtils.applyTransactionTimeout(stmt, getDataSource());
    stmt.executeUpdate("update " + getIncrementerName() + " set " + columnName +
        " = last_insert_id(" + columnName + " + " + getCacheSize() + ")");
  ResultSet rs = stmt.executeQuery(VALUE_SQL);
  try {
    if (!rs.next()) {
      throw new DataAccessResourceFailureException("last_insert_id() failed after executing an update");
    this.maxId = rs.getLong(1);
origin: spring-projects/spring-framework

  @Test
  public void testValid() throws Exception {
    String sql = "SELECT NAME AS NAME, PROPERTY AS PROPERTY, VALUE AS VALUE FROM T";

    Connection connection = mock(Connection.class);
    DataSource dataSource = mock(DataSource.class);
    given(dataSource.getConnection()).willReturn(connection);

    ResultSet resultSet = mock(ResultSet.class);
    given(resultSet.next()).willReturn(true, true, false);
    given(resultSet.getString(1)).willReturn("one", "one");
    given(resultSet.getString(2)).willReturn("(class)", "age");
    given(resultSet.getString(3)).willReturn("org.springframework.tests.sample.beans.TestBean", "53");

    Statement statement = mock(Statement.class);
    given(statement.executeQuery(sql)).willReturn(resultSet);
    given(connection.createStatement()).willReturn(statement);

    DefaultListableBeanFactory bf = new DefaultListableBeanFactory();
    JdbcBeanDefinitionReader reader = new JdbcBeanDefinitionReader(bf);
    reader.setDataSource(dataSource);
    reader.loadBeanDefinitions(sql);
    assertEquals("Incorrect number of bean definitions", 1, bf.getBeanDefinitionCount());
    TestBean tb = (TestBean) bf.getBean("one");
    assertEquals("Age in TestBean was wrong.", 53, tb.getAge());

    verify(resultSet).close();
    verify(statement).close();
  }
}
origin: spring-projects/spring-framework

@Test
public void testLeaveConnectionOpenOnRequest() throws Exception {
  String sql = "SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3";
  given(this.resultSet.next()).willReturn(false);
  given(this.connection.isClosed()).willReturn(false);
  given(this.connection.createStatement()).willReturn(this.preparedStatement);
  // if close is called entire test will fail
  willThrow(new RuntimeException()).given(this.connection).close();
  SingleConnectionDataSource scf = new SingleConnectionDataSource(this.dataSource.getConnection(), false);
  this.template = new JdbcTemplate(scf, false);
  RowCountCallbackHandler rcch = new RowCountCallbackHandler();
  this.template.query(sql, rcch);
  verify(this.resultSet).close();
  verify(this.preparedStatement).close();
}
origin: elasticjob/elastic-job-lite

private boolean updateJobExecutionEventWhenSuccess(final JobExecutionEvent jobExecutionEvent) {
  boolean result = false;
  String sql = "UPDATE `" + TABLE_JOB_EXECUTION_LOG + "` SET `is_success` = ?, `complete_time` = ? WHERE id = ?";
  try (
      Connection conn = dataSource.getConnection();
      PreparedStatement preparedStatement = conn.prepareStatement(sql)) {
    preparedStatement.setBoolean(1, jobExecutionEvent.isSuccess());
    preparedStatement.setTimestamp(2, new Timestamp(jobExecutionEvent.getCompleteTime().getTime()));
    preparedStatement.setString(3, jobExecutionEvent.getId());
    if (0 == preparedStatement.executeUpdate()) {
      return insertJobExecutionEventWhenSuccess(jobExecutionEvent);
    }
    result = true;
  } catch (final SQLException ex) {
    // TODO 记录失败直接输出日志,未来可考虑配置化
    log.error(ex.getMessage());
  }
  return result;
}

origin: alibaba/druid

public static <T> void executeQuery(DataSource dataSource
    , ResultSetConsumer<T> consumer
    , String sql
    , Object... parameters) throws SQLException {
  Connection conn = null;
  PreparedStatement stmt = null;
  ResultSet rs = null;
  try {
    conn = dataSource.getConnection();
    stmt = conn.prepareStatement(sql);
    for (int i = 0; i < parameters.length; ++i) {
      stmt.setObject(i + 1, parameters[i]);
    }
    rs = stmt.executeQuery();
    while (rs.next()) {
      if (consumer != null) {
        T object = consumer.apply(rs);
        consumer.accept(object);
      }
    }
  } finally {
    close(rs);
    close(stmt);
    close(conn);
  }
}
origin: spring-projects/spring-framework

@Before
public void setUp() throws Exception {
  this.connection = mock(Connection.class);
  this.dataSource = mock(DataSource.class);
  this.statement = mock(Statement.class);
  this.preparedStatement = mock(PreparedStatement.class);
  this.resultSet = mock(ResultSet.class);
  this.resultSetMetaData = mock(ResultSetMetaData.class);
  this.template = new JdbcTemplate(this.dataSource);
  given(this.dataSource.getConnection()).willReturn(this.connection);
  given(this.resultSet.getMetaData()).willReturn(this.resultSetMetaData);
  given(this.resultSetMetaData.getColumnCount()).willReturn(1);
  given(this.resultSetMetaData.getColumnLabel(1)).willReturn("age");
  given(this.connection.createStatement()).willReturn(this.statement);
  given(this.connection.prepareStatement(anyString())).willReturn(this.preparedStatement);
  given(this.preparedStatement.executeQuery()).willReturn(this.resultSet);
  given(this.statement.executeQuery(anyString())).willReturn(this.resultSet);
}
origin: stackoverflow.com

try
  InitialContext ctx = new InitialContext();
  this.src = (DataSource)ctx.lookup("jndi/MYSQL"); //The string should be the same name you're giving to your JNDI in Glassfish.
    this.con = src.getConnection();
    this.con.close();
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: 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: 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);
  }
}
javax.sqlDataSource

Javadoc

An interface for the creation of Connection objects which represent a connection to a database. This interface is an alternative to the java.sql.DriverManager.

A class which implements the DataSource interface is typically registered with a JNDI naming service directory and is retrieved from there by name.

The DataSource interface is typically implemented by the writer of a JDBC driver. There are three variants of the DataSource interface, which produce connections with different characteristics:

  1. Standard DataSource: produces standard Connectionobjects with no special features.
  2. Connection Pool DataSource: produces PooledConnection objects which require a connection pool manager as an intermediary component.
  3. Distributed transaction DataSource ("XADataSource"): produces XAConnection objects which can be used to handle distributed transactions which typically require an intermediary transaction manager component. XAConnection objects also provide connection pooling capabilities as well as distributed transaction capabilities.

Note that a JDBC driver which is accessed via the DataSourceinterface is loaded via a JNDI lookup process. A driver loaded in this way does not register itself with the DriverManager.

Most used methods

  • getConnection
    Attempts to establish a connection with the data source that this DataSource object represents.
  • setLogWriter
  • getLogWriter
  • setLoginTimeout
  • getLoginTimeout
  • unwrap
  • isWrapperFor
  • getParentLogger
  • <init>
  • createConnectionBuilder
  • createShardingKeyBuilder
  • createShardingKeyBuilder

Popular in Java

  • Making http requests using okhttp
  • runOnUiThread (Activity)
  • getApplicationContext (Context)
  • getExternalFilesDir (Context)
  • Color (java.awt)
    The Color class is used to encapsulate colors in the default sRGB color space or colors in arbitrary
  • Font (java.awt)
    The Font class represents fonts, which are used to render text in a visible way. A font provides the
  • Point (java.awt)
    A point representing a location in (x,y) coordinate space, specified in integer precision.
  • Calendar (java.util)
    Calendar is an abstract base class for converting between a Date object and a set of integer fields
  • Table (org.hibernate.mapping)
    A relational table
  • DateTimeFormat (org.joda.time.format)
    Factory that creates instances of DateTimeFormatter from patterns and styles. Datetime formatting i
  • Best plugins for Eclipse
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