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

How to use
Connection
in
java.sql

Best Java code snippets using java.sql.Connection (Showing top 20 results out of 28,314)

Refine searchRefine arrow

  • PreparedStatement
  • ResultSet
  • 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: spring-projects/spring-framework

/**
 * Return whether JDBC 3.0 Savepoints are supported.
 * Caches the flag for the lifetime of this ConnectionHolder.
 * @throws SQLException if thrown by the JDBC driver
 */
public boolean supportsSavepoints() throws SQLException {
  if (this.savepointsSupported == null) {
    this.savepointsSupported = getConnection().getMetaData().supportsSavepoints();
  }
  return this.savepointsSupported;
}
origin: alibaba/canal

public void commit() throws SQLException {
  getConn().commit();
  if (logger.isTraceEnabled()) {
    logger.trace("Batch executor commit " + idx.get() + " rows");
  }
  idx.set(0);
}
origin: prestodb/presto

@Override
public PreparedStatement getPreparedStatement(Connection connection, String sql)
    throws SQLException
{
  connection.setAutoCommit(false);
  PreparedStatement statement = connection.prepareStatement(sql);
  statement.setFetchSize(1000);
  return statement;
}
origin: spring-projects/spring-framework

/**
 * Prepare the given Connection before it is exposed.
 * <p>The default implementation applies the auto-commit flag, if necessary.
 * Can be overridden in subclasses.
 * @param con the Connection to prepare
 * @see #setAutoCommit
 */
protected void prepareConnection(Connection con) throws SQLException {
  Boolean autoCommit = getAutoCommitValue();
  if (autoCommit != null && con.getAutoCommit() != autoCommit) {
    con.setAutoCommit(autoCommit);
  }
}
origin: alibaba/druid

public boolean isValidConnection(final Connection c, String validateQuery, int validationQueryTimeout) throws Exception {
  if (c.isClosed()) {
    return false;
  }
  Statement stmt = null;
  try {
    stmt = c.createStatement();
    if (validationQueryTimeout > 0) {
      stmt.setQueryTimeout(validationQueryTimeout);
    }
    stmt.execute(validateQuery);
    return true;
  } catch (SQLException e) {
    throw e;
  } finally {
    JdbcUtils.close(stmt);
  }
}
origin: spring-projects/spring-framework

@Test
public void testHanaSequenceMaxValueIncrementer() throws SQLException {
  given(dataSource.getConnection()).willReturn(connection);
  given(connection.createStatement()).willReturn(statement);
  given(statement.executeQuery("select myseq.nextval from dummy")).willReturn(resultSet);
  given(resultSet.next()).willReturn(true);
  given(resultSet.getLong(1)).willReturn(10L, 12L);
  HanaSequenceMaxValueIncrementer incrementer = new HanaSequenceMaxValueIncrementer();
  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: 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: 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: 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: apache/ignite

/**
 * @throws Exception If failed.
 */
@Test
public void testPortRangeConnect() throws Exception {
  try (Connection conn = DriverManager.getConnection(URL_PORT_RANGE)) {
    try (Statement stmt = conn.createStatement()) {
      stmt.execute("SELECT 1");
      ResultSet rs = stmt.getResultSet();
      assertTrue(rs.next());
      assertEquals(1, rs.getInt(1));
    }
  }
}
origin: hibernate/hibernate-orm

public static void selectAllEmployments(ResultSet[] resultSets) throws SQLException {
  Connection conn = DriverManager.getConnection( "jdbc:default:connection" );
  PreparedStatement statement = conn.prepareStatement(
      "select EMPLOYEE, EMPLOYER, STARTDATE, ENDDATE," +
          " REGIONCODE, EMPID, 'VALUE', CURRENCY" +
          " FROM EMPLOYMENT"
  );
  resultSets[0] = statement.executeQuery();
  conn.close();
}
origin: spring-projects/spring-framework

@Test
public void testSqlUpdateWithThreadConnection() throws Exception {
  final String sql = "UPDATE NOSUCHTABLE SET DATE_DISPATCHED = SYSDATE WHERE ID = 4";
  int rowsAffected = 33;
  given(this.statement.executeUpdate(sql)).willReturn(rowsAffected);
  given(this.connection.createStatement()).willReturn(this.statement);
  int actualRowsAffected = this.template.update(sql);
  assertTrue("Actual rows affected is correct", actualRowsAffected == rowsAffected);
  verify(this.statement).close();
  verify(this.connection).close();
}
origin: iluwatar/java-design-patterns

/**
 * {@inheritDoc}
 */
@Override
public Optional<Customer> getById(int id) throws Exception {
 ResultSet resultSet = null;
 try (Connection connection = getConnection();
   PreparedStatement statement = 
     connection.prepareStatement("SELECT * FROM CUSTOMERS WHERE ID = ?")) {
  statement.setInt(1, id);
  resultSet = statement.executeQuery();
  if (resultSet.next()) {
   return Optional.of(createCustomer(resultSet));
  } else {
   return Optional.empty();
  }
 } catch (SQLException ex) {
  throw new CustomException(ex.getMessage(), ex);
 } finally {
  if (resultSet != null) {
   resultSet.close();
  }
 }
}
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: apache/incubator-druid

private void testAvaticaQuery(String url)
{
 LOG.info("URL: " + url);
 try {
  Properties connectionProperties = new Properties();
  connectionProperties.put("user", "admin");
  connectionProperties.put("password", "priest");
  Connection connection = DriverManager.getConnection(url, connectionProperties);
  Statement statement = connection.createStatement();
  statement.setMaxRows(450);
  String query = "SELECT * FROM INFORMATION_SCHEMA.COLUMNS";
  ResultSet resultSet = statement.executeQuery(query);
  Assert.assertTrue(resultSet.next());
  statement.close();
  connection.close();
 }
 catch (Exception e) {
  throw new RuntimeException(e);
 }
}
origin: stackoverflow.com

 public void create(User user) throws SQLException {
  try (
    Connection connection = dataSource.getConnection();
    PreparedStatement statement = connection.prepareStatement(SQL_INSERT,
                   Statement.RETURN_GENERATED_KEYS);
  ) {
    statement.setString(1, user.getName());
    statement.setString(2, user.getPassword());
    statement.setString(3, user.getEmail());
    // ...

    int affectedRows = statement.executeUpdate();

    if (affectedRows == 0) {
      throw new SQLException("Creating user failed, no rows affected.");
    }

    try (ResultSet generatedKeys = statement.getGeneratedKeys()) {
      if (generatedKeys.next()) {
        user.setId(generatedKeys.getLong(1));
      }
      else {
        throw new SQLException("Creating user failed, no ID obtained.");
      }
    }
  }
}
origin: spring-projects/spring-framework

@Test
public void testCouldNotClose() throws Exception {
  SQLException sqlException = new SQLException("bar");
  given(this.connection.createStatement()).willReturn(this.statement);
  given(this.resultSet.next()).willReturn(false);
  willThrow(sqlException).given(this.resultSet).close();
  willThrow(sqlException).given(this.statement).close();
  willThrow(sqlException).given(this.connection).close();
  RowCountCallbackHandler rcch = new RowCountCallbackHandler();
  this.template.query("SELECT ID, FORENAME FROM CUSTMR WHERE ID < 3", rcch);
  verify(this.connection).close();
}
java.sqlConnection

Javadoc

A connection represents a link from a Java application to a database. All SQL statements and results are returned within the context of a connection. Database statements that are executed within this context form a database session which forms one or more closed transactions. Especially in distributed applications, multiple concurrent connections may exist accessing the same values of the database. which may lead to the following phenomena (referred to as transaction isolation levels):
  • dirty reads:
    reading values from table rows that are not committed.
  • non-repeatable reads:
    reading table rows more than once in a transaction but getting back different data because other transactions have altered the rows between the reads.
  • phantom reads:
    retrieving additional "phantom" rows in the course of repeated table reads because other transactions have inserted additional rows that satisfy an SQL WHERE clause

Most used methods

  • close
    Causes the instant release of all database and driver connection resources associated with this obje
  • prepareStatement
    Creates a default PreparedStatement that can retrieve the auto-generated keys designated by a suppli
  • createStatement
    Returns a new instance of Statement whose associated ResultSets will have the characteristics specif
  • getMetaData
    Gets the metadata about the database referenced by this connection. The returned DatabaseMetaData de
  • commit
    Commits all of the changes made since the last commit or rollback of the associated transaction. All
  • setAutoCommit
    Sets this connection's auto-commit mode on or off. Putting a Connection into auto-commit mode means
  • rollback
    Undoes all changes made after the supplied Savepoint object was set. This method should only be used
  • isClosed
    Returns a boolean indicating whether or not this connection is in the closed state. The closed state
  • getAutoCommit
    Returns a boolean indicating whether or not this connection is in the auto-commit operating mode.
  • setTransactionIsolation
    Sets the transaction isolation level for this Connection. If this method is called during a transact
  • prepareCall
    Returns a new instance of CallableStatement that may be used for making stored procedure calls to th
  • getCatalog
    Gets this Connection object's current catalog name.
  • prepareCall,
  • getCatalog,
  • getTransactionIsolation,
  • setReadOnly,
  • isValid,
  • clearWarnings,
  • getWarnings,
  • setSavepoint,
  • isReadOnly,
  • setCatalog

Popular in Java

  • Making http requests using okhttp
  • findViewById (Activity)
  • scheduleAtFixedRate (Timer)
  • orElseThrow (Optional)
    Return the contained value, if present, otherwise throw an exception to be created by the provided s
  • BufferedWriter (java.io)
    Wraps an existing Writer and buffers the output. Expensive interaction with the underlying reader is
  • System (java.lang)
    Provides access to system-related information and resources including standard input and output. Ena
  • URL (java.net)
    A Uniform Resource Locator that identifies the location of an Internet resource as specified by RFC
  • Collection (java.util)
    Collection is the root of the collection hierarchy. It defines operations on data collections and t
  • Options (org.apache.commons.cli)
    Main entry-point into the library. Options represents a collection of Option objects, which describ
  • Loader (org.hibernate.loader)
    Abstract superclass of object loading (and querying) strategies. This class implements useful common
  • Best IntelliJ plugins
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