java.sql.Connection Java Examples

The following examples show how to use java.sql.Connection. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: JdbcTest.java    From java-jdbc with Apache License 2.0 7 votes vote down vote up
@Test
public void testFailOriginalUrl() throws Exception {
  TracingDriver.ensureRegisteredAsTheFirstDriver();
  TracingDriver.setInterceptorMode(true);
  try (Connection connection = DriverManager.getConnection("jdbc:h2:mem:jdbc")) {
    Statement statement = connection.createStatement();
    try {
      statement.executeUpdate("CREATE TABLE employer (id INTEGER2)");
    } catch (Exception ignore) {
    }
    assertGetDriver(connection);
  }

  List<MockSpan> spans = mockTracer.finishedSpans();
  assertEquals(2, spans.size());
  MockSpan span = spans.get(1);
  assertTrue(span.tags().containsKey(Tags.ERROR.getKey()));
  checkNoEmptyTags(spans);
}
 
Example #2
Source File: Procedure2Test.java    From gemfirexd-oss with Apache License 2.0 6 votes vote down vote up
public static void procedureWithInAndOutParameters(int number,
    String[] name,
    int[]    total,
    ResultSet[] rs1,
    ResultSet[] rs2, ResultSet[] rs3, ResultSet[] rs4) throws SQLException {
    Connection c = DriverManager.getConnection("jdbc:default:connection");
  
  name[0]=name[0]+"Modified";
  total[0]=number;
  
  if (number > 0) {
    rs1[0] = c.createStatement().executeQuery("VALUES(1)");
  }
  if (number > 1) {
    rs2[0] = c.createStatement().executeQuery("VALUES(1)");
  }
  if (number > 2) {
    rs3[0] = c.createStatement().executeQuery("VALUES(1)");
  }
  if (number > 3) {
    rs4[0] = c.createStatement().executeQuery("VALUES(1)");
  }
}
 
Example #3
Source File: LangProcedureTest.java    From spliceengine with GNU Affero General Public License v3.0 6 votes vote down vote up
public static void sqlControl2(String[] e1, String[] e2, String[] e3,
        String[] e4, String[] e5, String[] e6, String[] e7)
        throws SQLException {

    Connection conn = DriverManager
            .getConnection("jdbc:default:connection");

    Statement s = conn.createStatement();

    executeStatement(
            s,
            "CREATE VIEW SQLCONTROL_VIEW AS SELECT * FROM SQLC.SQLCONTROL_DML",
            e1);
    executeStatement(s, "DROP VIEW SQLCONTROL_VIEW", e2);

    executeStatement(s, "LOCK TABLE SQLC.SQLCONTROL_DML IN EXCLUSIVE MODE",
            e3);
    executeStatement(s, "VALUES 1,2,3", e4);
    executeStatement(s, "SET SCHEMA SQLC", e5);
    executeStatement(s, "CREATE SCHEMA SQLC_M", e6);
    executeStatement(s, "DROP SCHEMA SQLC_M RESTRICT", e7);

    conn.close();

}
 
Example #4
Source File: JDBCLinkStore.java    From qpid-broker-j with Apache License 2.0 6 votes vote down vote up
private void insert(final Connection connection,
                    final String linkKey,
                    final LinkDefinition<? extends BaseSource, ? extends BaseTarget> linkDefinition)
        throws SQLException
{
    try (PreparedStatement statement = connection.prepareStatement(String.format(
            "INSERT INTO %s (link_key, remote_container_id, link_name, link_role, source, target) VALUES (?,?,?,?,?,?)",
            getLinksTableName())))
    {
        statement.setString(1, linkKey);
        saveStringAsBlob(statement, 2, linkDefinition.getRemoteContainerId());
        saveStringAsBlob(statement, 3, linkDefinition.getName());
        statement.setInt(4, linkDefinition.getRole().getValue() ? 1 : 0);
        saveObjectAsBlob(statement, 5, linkDefinition.getSource());
        saveObjectAsBlob(statement, 6, linkDefinition.getTarget());
        if (statement.executeUpdate() != 1)
        {
            throw new StoreException(String.format("Cannot save link %s", new LinkKey(linkDefinition)));
        }
    }
}
 
Example #5
Source File: NumericArithmeticIT.java    From phoenix with Apache License 2.0 6 votes vote down vote up
@Test
public void testScanByUnsignedDoubleValue() throws Exception {
    String query = "SELECT a_string, b_string, a_unsigned_double FROM " + tableName + " WHERE ?=organization_id and ?=a_unsigned_double";
    Properties props = PropertiesUtil.deepCopy(TEST_PROPERTIES);
    Connection conn = DriverManager.getConnection(getUrl(), props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, getOrganizationId());
        statement.setDouble(2, 0.0001);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertEquals(rs.getString(1), A_VALUE);
        assertEquals(rs.getString("B_string"), B_VALUE);
        assertTrue(Doubles.compare(rs.getDouble(3), 0.0001) == 0);
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #6
Source File: DynamicSpringManagedTransaction.java    From hsweb-framework with Apache License 2.0 6 votes vote down vote up
@Override
public Connection getConnection() throws SQLException {
    TransactionProxy proxy = getProxy();
    if (proxy != null) {
        return proxy.getConnection();
    }
    //根据当前激活的数据源 获取jdbc链接
    DataSource dataSource = DataSourceHolder.currentDataSource().getNative();
    String dsId = switcher().currentDataSourceId();
    Connection connection = DataSourceUtils.getConnection(dataSource);
    proxy = new TransactionProxy(dsId, connection, dataSource);
    addProxy(proxy);

    if (LOGGER.isDebugEnabled()) {
        LOGGER.debug(
                "DataSource (" + (dsId == null ? "default" : dsId) + ") JDBC Connection ["
                        + connection
                        + "] will"
                        + (proxy.isConnectionTransactional ? " " : " not ")
                        + "be managed by Spring");
    }

    return connection;
}
 
Example #7
Source File: VersionDAO.java    From Knowage-Server with GNU Affero General Public License v3.0 6 votes vote down vote up
public void deleteVersions(Connection connection, String versionIds) throws Exception {
	logger.debug("IN");
	logger.debug("Deleting the versions " + versionIds + " from the cube");
	String editCubeTableName = getEditCubeName();
	Monitor deleteSQL = MonitorFactory.start("WhatIfEngine/it.eng.spagobi.engines.whatif.WhatIfEngineInstance.VersionDAO.deleteVersion.deleteMethodDAO.all");
	String sqlQuery = "delete from " + editCubeTableName + " where " + getVersionColumnName() + " in (" + versionIds + ")";

	Monitor deleteSQLExeCube = MonitorFactory.start("WhatIfEngine/it.eng.spagobi.engines.whatif.WhatIfEngineInstance.VersionDAO.deleteVersion.deleteMethodDAO.executeSQL.cube");
	SqlUpdateStatement queryStatement = new SqlUpdateStatement(sqlQuery);
	queryStatement.executeStatement(connection);
	deleteSQLExeCube.stop();
	
	
	logger.debug("Deleting the versions " + versionIds + " from the version dimension");
	sqlQuery = "delete from " + getVersionTableName() + " where " + getVersionColumnName() + " in (" + versionIds + ")";
	
	
	Monitor deleteSQLExeVersion = MonitorFactory.start("WhatIfEngine/it.eng.spagobi.engines.whatif.WhatIfEngineInstance.VersionDAO.deleteVersion.deleteMethodDAO.executeSQL.version");
	queryStatement = new SqlUpdateStatement(sqlQuery);
	queryStatement.executeStatement(connection);
	deleteSQLExeVersion.stop();
	
	logger.debug("Version deleted");
	logger.debug("OUT");
	deleteSQL.stop();
}
 
Example #8
Source File: AuthResourceCrudOperationsDao.java    From ballerina-message-broker with Apache License 2.0 6 votes vote down vote up
public boolean removeGroup(Connection connection, String resourceType, String resourceName,
                           String action, String group) throws AuthServerException {
    PreparedStatement insertMappingsStmt = null;
    try {
        insertMappingsStmt = connection.prepareStatement(RdbmsConstants.PS_DELETE_AUTH_RESOURCE_MAPPING);
        insertMappingsStmt.setString(1, resourceType);
        insertMappingsStmt.setString(2, resourceName);
        insertMappingsStmt.setString(3, action);
        insertMappingsStmt.setString(4, group);

        int updateRows = insertMappingsStmt.executeUpdate();

        return updateRows != 0;
    } catch (SQLException e) {
        throw new AuthServerException("Error occurred while persisting resource.", e);
    } finally {
        close(insertMappingsStmt);
    }
}
 
Example #9
Source File: AuthInfoDao.java    From hotelbook-JavaWeb with MIT License 6 votes vote down vote up
@Override
public ArrayList<AuthInfo> query(int start, int length) throws SQLException {

    Connection conn = DBUtil.getConnection();

    String sql = "select * from authInfo limit ?, ?;";
    PreparedStatement pstmt = conn.prepareStatement(sql);
    pstmt.setInt(1, start - 1);
    pstmt.setInt(2, length);
    ResultSet rs = pstmt.executeQuery();

    ArrayList<AuthInfo> list = new ArrayList<>();
    AuthInfo authInfo;

    while (rs.next()) {
        authInfo = new AuthInfo(rs.getInt(1), rs.getString(2), rs.getString(3)
                , rs.getString(4), rs.getString(5), rs.getString(6));
        list.add(authInfo);
    }

    rs.close();
    pstmt.close();

    return list;
}
 
Example #10
Source File: NarayanaDataSourceTests.java    From narayana-spring-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void shouldGetConnectionAndCommit() throws SQLException {
    Connection mockConnection = mock(Connection.class);
    XAConnection mockXaConnection = mock(XAConnection.class);
    given(mockXaConnection.getConnection()).willReturn(mockConnection);
    given(this.mockXaDataSource.getXAConnection()).willReturn(mockXaConnection);

    // TODO properties not used
    Properties properties = new Properties();
    properties.put(TransactionalDriver.XADataSource, this.mockXaDataSource);

    Connection connection = this.dataSourceBean.getConnection();
    assertThat(connection).isInstanceOf(ConnectionImple.class);

    connection.commit();

    verify(this.mockXaDataSource, times(1)).getXAConnection();
    verify(mockXaConnection, times(1)).getConnection();
    verify(mockConnection, times(1)).commit();
}
 
Example #11
Source File: DefaultRosterItemProvider.java    From Openfire with Apache License 2.0 6 votes vote down vote up
@Override
public Iterator<String> getUsernames(String jid) {
    List<String> answer = new ArrayList<>();
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(LOAD_USERNAMES);
        pstmt.setString(1, jid);
        rs = pstmt.executeQuery();
        while (rs.next()) {
            answer.add(rs.getString(1));
        }
    }
    catch (SQLException e) {
        Log.error(LocaleUtils.getLocalizedString("admin.error"), e);
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return answer.iterator();
}
 
Example #12
Source File: ArrayTypeTest.java    From calcite-avatica with Apache License 2.0 6 votes vote down vote up
@Test public void bigintArrays() throws Exception {
  final Random r = new Random();
  try (Connection conn = DriverManager.getConnection(url)) {
    ScalarType component = ColumnMetaData.scalar(Types.BIGINT, "BIGINT", Rep.LONG);
    List<Array> arrays = new ArrayList<>();
    // Construct the data
    for (int i = 0; i < 3; i++) {
      List<Long> elements = new ArrayList<>();
      for (int j = 0; j < 7; j++) {
        long element = r.nextLong();
        if (r.nextBoolean()) {
          element *= -1;
        }
        elements.add(element);
      }
      arrays.add(createArray("BIGINT", component, elements));
    }
    writeAndReadArrays(conn, "long_arrays", "BIGINT", component, arrays,
        PRIMITIVE_LIST_VALIDATOR);
  }
}
 
Example #13
Source File: MultiDBPreparedStatementLifeCycleTest.java    From Zebra with Apache License 2.0 6 votes vote down vote up
@Test
public void testSingleRouterResult0() throws Exception {
    DataSource ds = (DataSource) context.getBean("zebraDS");
    Connection conn = null;
    try {
        conn = ds.getConnection();
        PreparedStatement stmt = conn.prepareStatement("select name from test where id=?");
        stmt.setInt(1, 0);
        stmt.execute();
        ResultSet rs = stmt.getResultSet();
        List<String> rows = new ArrayList<String>();
        while (rs.next()) {
            rows.add(rs.getString("name"));
        }
        Assert.assertEquals(2, rows.size());
        Assert.assertEquals("leo0", rows.get(0));
        Assert.assertEquals("leo0", rows.get(1));
    } catch (Exception e) {
        Assert.fail();
    } finally {
        if (conn != null) {
            conn.close();
        }
    }
}
 
Example #14
Source File: QueryTest.java    From phoenix with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test
public void testCastOperatorInWhere() throws Exception {
    String query = "SELECT a_integer FROM aTable WHERE ?=organization_id and 2.5 = (CAST a_integer AS DECIMAL)/2 ";
    Properties props = new Properties(TEST_PROPERTIES);
    props.setProperty(PhoenixRuntime.CURRENT_SCN_ATTRIB, Long.toString(ts + 2)); // Execute at timestamp 2
    Connection conn = DriverManager.getConnection(PHOENIX_JDBC_URL, props);
    try {
        PreparedStatement statement = conn.prepareStatement(query);
        statement.setString(1, tenantId);
        ResultSet rs = statement.executeQuery();
        assertTrue (rs.next());
        assertEquals(5, rs.getInt(1));
        assertFalse(rs.next());
    } finally {
        conn.close();
    }
}
 
Example #15
Source File: TestTransactionalClientPortal.java    From reladomo with Apache License 2.0 6 votes vote down vote up
public int serverCheckDatedBitemporalRowCounts(int balanceId) throws SQLException
{
    Connection con = this.getServerSideConnection();
    String sql = "select count(*) from TINY_BALANCE where BALANCE_ID = ?";
    PreparedStatement ps = con.prepareStatement(sql);
    ps.setInt(1, balanceId);
    ResultSet rs = ps.executeQuery();
    assertTrue(rs.next());

    int counts = rs.getInt(1);
    assertFalse(rs.next());
    rs.close();
    ps.close();
    con.close();

    return counts;
}
 
Example #16
Source File: IoTDBTagIT.java    From incubator-iotdb with Apache License 2.0 6 votes vote down vote up
@Test
public void createDuplicateAliasTimeseriesTest2() throws ClassNotFoundException {
  String sql1 = "create timeseries root.turbine.d4.s1(temperature) with datatype=FLOAT, encoding=RLE, compression=SNAPPY " +
          "tags(tag1=t1, tag2=t2) attributes(attr1=a1, attr2=a2)";
  String sql2 = "create timeseries root.turbine.d4.temperature with datatype=INT32, encoding=RLE " +
          "tags(tag2=t2, tag3=t3) attributes(attr3=a3, attr4=a4)";
  Class.forName(Config.JDBC_DRIVER_NAME);
  try (Connection connection = DriverManager
          .getConnection(Config.IOTDB_URL_PREFIX + "127.0.0.1:6667/", "root", "root");
       Statement statement = connection.createStatement()) {
    statement.execute(sql1);
    statement.execute(sql2);
    fail();
  } catch (Exception e) {
    assertTrue(e.getMessage().contains("Path [root.turbine.d4.temperature] already exist"));
  }
}
 
Example #17
Source File: SnowflakeSourceOrSinkTest.java    From components with Apache License 2.0 6 votes vote down vote up
@Test
public void testValidateConnection() throws Exception {
    SnowflakeConnectionProperties properties = new SnowflakeConnectionProperties("connection");
    properties.account.setValue("talend");
    properties.userPassword.password.setValue("teland_password");
    properties.userPassword.userId.setValue("talend_dev");
    properties.schemaName.setValue("LOAD");
    properties.db.setValue("TestDB");
    Connection connection = Mockito.mock(Connection.class);
    Mockito.when(connection.isClosed()).thenReturn(false);
    DatabaseMetaData metaData = Mockito.mock(DatabaseMetaData.class);
    Mockito.when(metaData.getTables(Mockito.any(), Mockito.any(), Mockito.any(),
            Mockito.eq(new String[] { "TABLE", "VIEW" }))).thenReturn(Mockito.mock(ResultSet.class));
    Mockito.when(connection.getMetaData()).thenReturn(metaData);
    Mockito.when(
            DriverManagerUtils.getConnection(Mockito.any()))
    .thenReturn(connection);

    SnowflakeSourceOrSink sss = new SnowflakeSourceOrSink();
    sss.initialize(null, properties);
    Assert.assertEquals(ValidationResult.Result.OK, sss.validateConnection(properties).getStatus());
}
 
Example #18
Source File: savepointJdbc30_JSR169.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
public static void doConnectionSetSavepointUnnamed() throws Throwable
{
	Connection conn = DriverManager.getConnection("jdbc:default:connection");
	Savepoint s1 = conn.setSavepoint();
	Statement s = conn.createStatement();
	s.executeUpdate("insert into t2 values(1)");
	conn.rollback(s1);
}
 
Example #19
Source File: AbstractPipelineMavenPluginDao.java    From pipeline-maven-plugin with MIT License 5 votes vote down vote up
protected int getSchemaVersion(Connection cnn) throws SQLException {
    int schemaVersion;
    try (Statement stmt = cnn.createStatement()) {
        try (ResultSet rst = stmt.executeQuery("SELECT * FROM VERSION")) {
            if (rst.next()) {
                schemaVersion = rst.getInt(1);
            } else {
                schemaVersion = 0;
            }
        } catch (SQLException e) {
            if (e.getErrorCode() == ErrorCode.TABLE_OR_VIEW_NOT_FOUND_1) {
                // H2 TABLE_OR_VIEW_NOT_FOUND_1
                schemaVersion = 0;
            } else if (e.getErrorCode() == 1146) {
                // MySQL TABLE_OR_VIEW_NOT_FOUND_1
                schemaVersion = 0;
            } else if ("42P01".equals(e.getSQLState())) {
                // ignore PostgreSQL "ERROR: relation "..." does not exist
                schemaVersion = 0;
                cnn.rollback(); // postgresql requires to rollback after a 42P01 error
            } else {
                throw new RuntimeSqlException(e);
            }
        }
    }
    return schemaVersion;
}
 
Example #20
Source File: UpsertSelectIT.java    From phoenix with Apache License 2.0 5 votes vote down vote up
private Connection getTenantConnection(String tenantId) throws Exception {
    Properties props = PropertiesUtil.deepCopy(TestUtil.TEST_PROPERTIES);
    props.setProperty(QueryServices.ENABLE_SERVER_SIDE_UPSERT_MUTATIONS,
        allowServerSideMutations);
    props.setProperty(TENANT_ID_ATTRIB, tenantId);
    return DriverManager.getConnection(getUrl(), props);
}
 
Example #21
Source File: FabricMultiTenantConnectionProvider.java    From r-course with MIT License 5 votes vote down vote up
/**
 * Find a server with mode READ_WRITE in the given server group and create a JDBC connection to it.
 * 
 * @returns a {@link Connection} to an arbitrary MySQL server
 * @throws SQLException
 *             if connection fails or a READ_WRITE server is not contained in the group
 */
private Connection getReadWriteConnectionFromServerGroup(ServerGroup serverGroup) throws SQLException {
    for (Server s : serverGroup.getServers()) {
        if (ServerMode.READ_WRITE.equals(s.getMode())) {
            String jdbcUrl = String.format("jdbc:mysql://%s:%s/%s", s.getHostname(), s.getPort(), this.database);
            return DriverManager.getConnection(jdbcUrl, this.user, this.password);
        }
    }
    throw new SQLException("Unable to find r/w server for chosen shard mapping in group " + serverGroup.getName());
}
 
Example #22
Source File: Bug3506138.java    From spotbugs with GNU Lesser General Public License v2.1 5 votes vote down vote up
@ExpectWarning("ODR_OPEN_DATABASE_RESOURCE")
public static void test0(String url) throws Exception {
    Connection conn;
    PreparedStatement pstm = null;
    try {
        conn = DriverManager.getConnection(url);
        pstm = conn.prepareStatement("123");
        pstm.executeUpdate();
    } finally {
        if (pstm != null)
            pstm.close();
    }
}
 
Example #23
Source File: BroadcastJoinMemoryLimitIT.java    From spliceengine with GNU Affero General Public License v3.0 5 votes vote down vote up
public static void createData(Connection conn, String schemaName) throws Exception {

        new TableCreator(conn)
                .withCreate("create table t2 (a2 int, b2 int, c2 int, d2 varchar(10000))")
                .withInsert("insert into t2 values(?,?,?,?)")
                .withRows(rows(
                        row(1,1,1,"a"),
                        row(2,2,2,"b"),
                        row(3,3,3,"c"),
                        row(4,4,4,"d"),
                        row(5,5,5,"e"),
                        row(6,6,6,"f"),
                        row(7,7,7,"g"),
                        row(8,8,8,"h"),
                        row(9,9,9,"i"),
                        row(10,10,10,"j")))
                .create();

        new TableCreator(conn)
                .withCreate("create table t1 (a1 int, b1 int, c1 int, d1 varchar(10000))")
                .create();

        conn.createStatement().executeQuery(format(
                "CALL SYSCS_UTIL.FAKE_TABLE_STATISTICS('%s','T1', 100000000, 10050, 1)",
                schemaName));

        conn.createStatement().executeQuery(format(
                "CALL SYSCS_UTIL.FAKE_TABLE_STATISTICS('%s','T2', 5000, 10050, 1)",
                schemaName));

        conn.createStatement().executeQuery(format(
                "CALL SYSCS_UTIL.FAKE_COLUMN_STATISTICS('%s','T2', 'A2', 0, 500)",
                schemaName));



        conn.commit();
    }
 
Example #24
Source File: ApplicationTests.java    From spring-boot-projects with Apache License 2.0 5 votes vote down vote up
@Test
public void datasourceTest() throws SQLException {
    // 获取数据源类型
    System.out.println("默认数据源为:" + dataSource.getClass());
    // 获取数据库连接对象
    Connection connection = dataSource.getConnection();
    // 判断连接对象是否为空
    System.out.println(connection != null);
    connection.close();
}
 
Example #25
Source File: PhoenixDriverTest.java    From phoenix with Apache License 2.0 5 votes vote down vote up
@Test
public void testFirstConnectionWhenPropsHasTenantId() throws Exception {
    Properties props = new Properties();
    final String tenantId = "00Dxx0000001234";
    props.put(PhoenixRuntime.TENANT_ID_ATTRIB, tenantId);

    Connection connection = new PhoenixTestDriver().connect(getUrl(), props);
    assertEquals(tenantId, connection.getClientInfo(PhoenixRuntime.TENANT_ID_ATTRIB));
}
 
Example #26
Source File: NonFullyQualifiedNamespaceTest.java    From mybaties with Apache License 2.0 5 votes vote down vote up
@Test
public void testCrossReferenceXmlConfig() throws Exception {
    Reader configReader = Resources
            .getResourceAsReader("org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespaceConfig.xml");
    SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(configReader);
    configReader.close();

    Configuration configuration = sqlSessionFactory.getConfiguration();

    MappedStatement selectPerson = configuration.getMappedStatement("person namespace.select");
    assertEquals(
            "org/apache/ibatis/submitted/xml_external_ref/NonFullyQualifiedNamespacePersonMapper.xml",
            selectPerson.getResource());

    Connection conn = configuration.getEnvironment().getDataSource().getConnection();
    initDb(conn);

    SqlSession sqlSession = sqlSessionFactory.openSession();
    try {
        Person person = (Person) sqlSession.selectOne("person namespace.select", 1);
        assertEquals((Integer)1, person.getId());
        assertEquals(2, person.getPets().size());
        assertEquals((Integer)2, person.getPets().get(1).getId());

        Pet pet = (Pet) sqlSession.selectOne("person namespace.selectPet", 1);
        assertEquals(Integer.valueOf(1), pet.getId());

        Pet pet2 = (Pet) sqlSession.selectOne("pet namespace.select", 3);
        assertEquals((Integer)3, pet2.getId());
        assertEquals((Integer)2, pet2.getOwner().getId());
    }
    finally {
        sqlSession.close();
    }
}
 
Example #27
Source File: DefaultSequenceHandlerRepository.java    From pnc with Apache License 2.0 5 votes vote down vote up
@Override
public Long getNextID(final String sequenceName) {

    ReturningWork<Long> maxReturningWork = new ReturningWork<Long>() {
        @Override
        public Long execute(Connection connection) throws SQLException {
            DialectResolver dialectResolver = new StandardDialectResolver();
            Dialect dialect = dialectResolver.resolveDialect(getResolutionInfo(connection));
            PreparedStatement preparedStatement = null;
            ResultSet resultSet = null;
            try {
                preparedStatement = connection.prepareStatement(dialect.getSequenceNextValString(sequenceName));
                resultSet = preparedStatement.executeQuery();
                resultSet.next();
                return resultSet.getLong(1);
            } catch (SQLException e) {
                throw e;
            } finally {
                if (preparedStatement != null) {
                    preparedStatement.close();
                }
                if (resultSet != null) {
                    resultSet.close();
                }
            }

        }
    };

    Session session = (Session) entityManager.getDelegate();
    SessionFactory sessionFactory = session.getSessionFactory();

    Long maxRecord = sessionFactory.getCurrentSession().doReturningWork(maxReturningWork);
    return maxRecord;
}
 
Example #28
Source File: ExternalComponentManager.java    From Openfire with Apache License 2.0 5 votes vote down vote up
private static Collection<ExternalComponentConfiguration> getConfigurations(
        Permission permission) {
    Collection<ExternalComponentConfiguration> answer =
            new ArrayList<>();
    Connection con = null;
    PreparedStatement pstmt = null;
    ResultSet rs = null;
    try {
        con = DbConnectionManager.getConnection();
        pstmt = con.prepareStatement(LOAD_CONFIGURATIONS);
        pstmt.setString(1, permission.toString());
        rs = pstmt.executeQuery();
        ExternalComponentConfiguration configuration;
        while (rs.next()) {
            String subdomain = rs.getString(1);
            boolean wildcard = rs.getInt(2) == 1;
            // Remove the trailing % if using wildcards
            subdomain = wildcard ? subdomain.substring(0, subdomain.length()-1) : subdomain;
            configuration = new ExternalComponentConfiguration(subdomain, wildcard, permission,
                    rs.getString(3));
            answer.add(configuration);
        }
    }
    catch (SQLException sqle) {
        Log.error(sqle.getMessage(), sqle);
    }
    finally {
        DbConnectionManager.closeConnection(rs, pstmt, con);
    }
    return answer;
}
 
Example #29
Source File: MBeanTest.java    From gemfirexd-oss with Apache License 2.0 5 votes vote down vote up
private void doProcedureCall() throws SQLException {
  int times = HydraUtil.getnextNonZeroRandomInt(10);
  Connection conn = getGFEConnection();
//  printOpenConnection("doProcedureCall");
  CallableStatement cs;
  
  String procName = HydraUtil.getRandomElement(new String[] { "trade.show_customers(?)", "trade.longRunningProcedure(?)" });
  String sql = "CALL  " + procName + " ON ALL";
  cs = conn.prepareCall(sql);
  Log.getLogWriter().info("Executing proc sql " + sql);
  for (int i = 0; i < times; i++) {
    try {
      Log.getLogWriter().info("Running Procedure : " + procName);
      int counter = isEdge ? incrementCounter(COUNTER_MBEAN_PROC_CALLS_IN_PROGRESS_EDGE) : incrementCounter(COUNTER_MBEAN_PROC_CALLS_IN_PROGRESS);
      cs.setInt(1, RemoteTestModule.getCurrentThread().getThreadId());
      cs.execute();
      counter = isEdge ? incrementCounter(COUNTER_MBEAN_PROC_CALLS_EDGE) : incrementCounter(COUNTER_MBEAN_PROC_CALLS);
    } catch(SQLException e) {
      if (e.getSQLState().equals("XCL54")) {
        Log.getLogWriter().warning("Error occurred while executing query : " + sql + ", Low Memory Exception");
      } else {
        throw e;
      }
    } finally {
      if(isEdge) {
        decrementCounter(COUNTER_MBEAN_PROC_CALLS_IN_PROGRESS_EDGE);
      } else {
        decrementCounter(COUNTER_MBEAN_PROC_CALLS_IN_PROGRESS);
      }
      
      Log.getLogWriter().info("Procedure Completed : " + procName);
    }
  }
  
  cs.close();
}
 
Example #30
Source File: JDBCRendicontazioneServiceSearchImpl.java    From govpay with GNU General Public License v3.0 5 votes vote down vote up
@Override
public Object aggregate(JDBCServiceManagerProperties jdbcProperties, Logger log, Connection connection, ISQLQueryObject sqlQueryObject, 
												JDBCExpression expression, FunctionField functionField) throws ServiceException,NotFoundException,NotImplementedException,Exception {
	Map<String,Object> map = 
		this.aggregate(jdbcProperties, log, connection, sqlQueryObject, expression, new FunctionField[]{functionField});
	return org.openspcoop2.generic_project.dao.jdbc.utils.JDBCUtilities.selectAggregateObject(map,functionField);
}