Java 类java.sql.SQLException 实例源码

项目:plugin-bt-jira    文件:JiraUpdateDaoTest.java   
/**
 * Initialize data base with 'MDA' JIRA project.
 */
@BeforeClass
public static void initializeJiraDataBaseForImport() throws SQLException {
    datasource = new SimpleDriverDataSource(new JDBCDriver(), "jdbc:hsqldb:mem:dataSource", null, null);
    final Connection connection = datasource.getConnection();
    try {
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-1/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/base-2/jira-create.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection,
                new EncodedResource(new ClassPathResource("sql/upload/jira-create.sql"), StandardCharsets.UTF_8));

        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-1/jira.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/base-2/jira.sql"), StandardCharsets.UTF_8));
        ScriptUtils.executeSqlScript(connection, new EncodedResource(new ClassPathResource("sql/upload/jira.sql"), StandardCharsets.UTF_8));
    } finally {
        connection.close();
    }
}
项目:spr    文件:SqlDelete.java   
public static void deleteProductoPresupuesto(String id, String producto_id, String producto_unidad_medida_id, String proyecto_id, String proyecto_subprograma_id, String proyecto_subprograma_programa_id, String proyecto_subprograma_programa_tipo_presupuesto_id, String proyecto_subprograma_programa_entidad_id, String proyecto_subprograma_programa_entidad_nivel_id){
     Connection conect=ConnectionConfiguration.conectar();
     Statement statement = null;
 String                                                         query = "delete from producto_presupusto ";
 //if (id!="")                                                  query+= "id=\""+id+"\", ";
 /*if (numero_fila!="")                                         query+= "numero_fila=\""+numero_fila+"\", ";
 if (anho!="")                                                  query+= "anho=\""+anho+"\", ";
 //if (producto_id!="")                                         query+= "producto_id=\""+producto_id+"\", ";
 //if (producto_unidad_medida_id!="")                           query+= "producto_unidad_medida_id=\""+producto_unidad_medida_id+"\", ";
 //if (proyecto_id!="")                                         query+= "proyecto_id=\""+proyecto_id+"\", ";
 //if (proyecto_subprograma_id!="")                             query+= "proyecto_subprograma_id=\""+proyecto_subprograma_id+"\", ";
 //if (proyecto_subprograma_programa_id!="")                    query+= "proyecto_subprograma_programa_id=\""+proyecto_subprograma_programa_id+"\", ";
 //if (proyecto_subprograma_programa_tipo_presupuesto_id!="")   query+= "proyecto_subprograma_programa_tipo_presupuesto_id=\""+proyecto_subprograma_programa_tipo_presupuesto_id+"\", ";
 //if (proyecto_subprograma_programa_entidad_id!="")            query+= "proyecto_subprograma_programa_entidad_id=\""+proyecto_subprograma_programa_entidad_id+"\", ";
 //if (proyecto_subprograma_programa_entidad_nivel_id!="")      query+= "proyecto_subprograma_programa_entidad_nivel_id=\""+proyecto_subprograma_programa_entidad_nivel_id+"\", ";
 if (version!="")           query+= "version=\""+version+"\", ";
 query = query.substring(0, query.length()-2);*/
 query+="where id="+id+" and producto_id="+producto_id+" and producto_unidad_medida_id="+producto_unidad_medida_id+" and proyecto_id="+proyecto_id+" and proyecto_subprograma_id="+proyecto_subprograma_id+" and proyecto_subprograma_programa_id="+proyecto_subprograma_programa_id+" and proyecto_subprograma_programa_tipo_presupuesto_id="+proyecto_subprograma_programa_tipo_presupuesto_id+" and proyecto_subprograma_programa_entidad_id="+proyecto_subprograma_programa_entidad_id+" and proyecto_subprograma_programa_entidad_nivel_id="+proyecto_subprograma_programa_entidad_nivel_id;

try {
    statement=conect.createStatement();
    statement.execute(query);
    conect.close();
} catch (SQLException e) {e.printStackTrace();}
 }
项目:BibliotecaPS    文件:JDBC4ConnectionWrapper.java   
public void setClientInfo(String name, String value) throws SQLClientInfoException {
    try {
        checkClosed();

        ((java.sql.Connection) this.mc).setClientInfo(name, value);
    } catch (SQLException sqlException) {
        try {
            checkAndFireConnectionError(sqlException);
        } catch (SQLException sqlEx2) {
            SQLClientInfoException clientEx = new SQLClientInfoException();
            clientEx.initCause(sqlEx2);

            throw clientEx;
        }
    }
}
项目:Nird2    文件:JdbcDatabase.java   
@Override
public void lowerRequestedFlag(Connection txn, ContactId c,
        Collection<MessageId> requested) throws DbException {
    PreparedStatement ps = null;
    try {
        String sql = "UPDATE statuses SET requested = FALSE"
                + " WHERE messageId = ? AND contactId = ?";
        ps = txn.prepareStatement(sql);
        ps.setInt(2, c.getInt());
        for (MessageId m : requested) {
            ps.setBytes(1, m.getBytes());
            ps.addBatch();
        }
        int[] batchAffected = ps.executeBatch();
        if (batchAffected.length != requested.size())
            throw new DbStateException();
        for (int rows: batchAffected) {
            if (rows < 0) throw new DbStateException();
            if (rows > 1) throw new DbStateException();
        }
        ps.close();
    } catch (SQLException e) {
        tryToClose(ps);
        throw new DbException(e);
    }
}
项目:DMS    文件:LoadGoingoutApplyStatus.java   
@Override
public void handle(RoutingContext ctx) {
    EasyJsonObject responseObject = new EasyJsonObject();

       if(UserManager.isLogined(ctx)) {
        try {
            UserManager.getUserInfo(UserManager.getIdFromSession(ctx));
            boolean[] status = UserManager.getOutStatus(UserManager.getIdFromSession(ctx));
            responseObject.put("sat", status[0]);
            responseObject.put("sun", status[1]);
            ctx.response().setStatusCode(200).end(responseObject.toString());
            ctx.response().close();
        } catch (SQLException e) {
            ctx.response().setStatusCode(500).end();
            ctx.response().close();

            Log.l("SQLException");
        }
    }else{
        ctx.response().setStatusCode(400).end();
        ctx.response().close();
        return;
    }
}
项目:ProyectoPacientes    文件:MysqlPooledConnection.java   
/**
 * Notifies all registered ConnectionEventListeners of ConnectionEvents.
 * Instantiates a new ConnectionEvent which wraps sqlException and invokes
 * either connectionClose or connectionErrorOccurred on listener as
 * appropriate.
 * 
 * @param eventType
 *            value indicating whether connectionClosed or
 *            connectionErrorOccurred called
 * @param sqlException
 *            the exception being thrown
 */
protected synchronized void callConnectionEventListeners(int eventType, SQLException sqlException) {

    if (this.connectionEventListeners == null) {

        return;
    }

    Iterator<Map.Entry<ConnectionEventListener, ConnectionEventListener>> iterator = this.connectionEventListeners.entrySet().iterator();

    ConnectionEvent connectionevent = new ConnectionEvent(this, sqlException);

    while (iterator.hasNext()) {

        ConnectionEventListener connectioneventlistener = iterator.next().getValue();

        if (eventType == CONNECTION_CLOSED_EVENT) {
            connectioneventlistener.connectionClosed(connectionevent);
        } else if (eventType == CONNECTION_ERROR_EVENT) {
            connectioneventlistener.connectionErrorOccurred(connectionevent);
        }
    }
}
项目:hotelbook-JavaWeb    文件:FloorInfoServiceImpl.java   
@Override
public int queryRepeat(String newName, String oldName) {
    FloorInfo floorInfoQuery = new FloorInfo();
    floorInfoQuery.setFloorName(newName);
    FloorInfo floorInfo;
    try {
        floorInfo = (FloorInfo) dao.query(floorInfoQuery);
        if (!floorInfo.isNull()) { //表示存在同名项
            if (floorInfo.getFloorName().equals(oldName))
                return 2; //表示存在同名项,但是是与传递来的相同
            return 0;
        } else
            return 1;
    } catch (SQLException e) {
        System.out.println(e.getErrorCode() + e.getMessage());
        return -1;
    }
}
项目:incubator-netbeans    文件:QueryBuilderMetaData.java   
/**
 * Returns the Foreign Key Constraints that apply to the specified table
 *
 * Result is an a-list of <foreignTable, foreignCol, primTable, primCol>.
 */
List getForeignKeys(String fullTableName) throws SQLException {

    Log.getLogger().entering("QueryBuilderMetaData", "getForeignKeys", fullTableName); // NOI18N
    // keys.add(new String[] {"travel.trip", "personid", "travel.person", "personid"});
    // We get the exported keys (foreign tables that reference this one), then
    // imported keys (foreign tables that this one references).
    /*
    List keys = getForeignKeys1(fullTableName, true);
    keys.addAll(getForeignKeys1(fullTableName, false));
     */
    String[] tableSpec = parseTableName(fullTableName);
    List<List<String>> keys = getImportedKeys(tableSpec[0], tableSpec[1]);
    keys.addAll(getExportedKeys(tableSpec[0], tableSpec[1]));

    // Convert to a List(String[]), for compatibility with the rest of the QueryEditor
    List result = new ArrayList();
    for (List<String> key : keys) {
        result.add(key.toArray());
    }
    return result;
}
项目:parabuild-ci    文件:TestCascade.java   
private static void createDatabase() throws SQLException {

        new File("testdb.backup").delete();
        new File("testdb.data").delete();
        new File("testdb.properties").delete();
        new File("testdb.script").delete();

        Connection con = DriverManager.getConnection("jdbc:hsqldb:testdb",
            "sa", "");
        String[] saDDL = {
            "CREATE CACHED TABLE XB (EIACODXA VARCHAR(10) NOT NULL, LSACONXB VARCHAR(18) NOT NULL, ALTLCNXB VARCHAR(2) NOT NULL, LCNTYPXB VARCHAR(1) NOT NULL, LCNINDXB VARCHAR(1), LCNAMEXB VARCHAR(19), UPDT_BY VARCHAR(32), LST_UPDT TIMESTAMP, CONSTRAINT XPKXB PRIMARY KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB));",
            "CREATE INDEX XIF2XB ON XB (EIACODXA);",
            "CREATE CACHED TABLE CA ( EIACODXA VARCHAR(10) NOT NULL, LSACONXB VARCHAR(18) NOT NULL, ALTLCNXB VARCHAR(2) NOT NULL, LCNTYPXB VARCHAR(1) NOT NULL, TASKCDCA VARCHAR(7) NOT NULL, TSKFRQCA NUMERIC(7,4), UPDT_BY VARCHAR(32), LST_UPDT TIMESTAMP, CONSTRAINT XPKCA PRIMARY KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB, TASKCDCA),        CONSTRAINT R_XB_CA FOREIGN KEY (EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB) REFERENCES XB ON DELETE CASCADE);",
            "CREATE INDEX XIF26CA ON CA ( EIACODXA, LSACONXB, ALTLCNXB, LCNTYPXB);"
        };
        Statement stmt = con.createStatement();

        for (int index = 0; index < saDDL.length; index++) {
            stmt.executeUpdate(saDDL[index]);
        }

        con.close();
    }
项目:the-vigilantes    文件:JDBC4ClientInfoProviderSP.java   
public synchronized void setClientInfo(java.sql.Connection conn, Properties properties) throws SQLClientInfoException {
    try {
        Enumeration<?> propNames = properties.propertyNames();

        while (propNames.hasMoreElements()) {
            String name = (String) propNames.nextElement();
            String value = properties.getProperty(name);

            setClientInfo(conn, name, value);
        }
    } catch (SQLException sqlEx) {
        SQLClientInfoException clientInfoEx = new SQLClientInfoException();
        clientInfoEx.initCause(sqlEx);

        throw clientInfoEx;
    }
}
项目:HueSense    文件:PresenceSensor.java   
@Override
public Set<SensorValue<Boolean>> getValuesInRange(Date start, Date end) {
    NavigableSet<SensorValue<Boolean>> ret = new TreeSet<>();

    try (Connection conn = dbMan.getConnection()) {
        try (PreparedStatement stmt = conn.prepareStatement(SELECT_RANGE)) {
            stmt.setLong(1, dbId);
            stmt.setTimestamp(2, new Timestamp(start.getTime()));
            long endTime = end == null ? System.currentTimeMillis() : end.getTime();
            stmt.setTimestamp(3, new Timestamp(endTime));
            ResultSet rs = stmt.executeQuery();
            while (rs.next()) {
                SensorValue<Boolean> val = new SensorValue<>(rs.getTimestamp("CREATED"), rs.getBoolean("PRESENCE"));
                ret.add(val);
            }
        }
    } catch (SQLException ex) {
        LOG.error("Error querying light values", ex);
    }
    return ret;
}
项目:parabuild-ci    文件:TestCacheSize.java   
private void countZip() {

        try {
            StopWatch sw = new StopWatch();

            sStatement.execute("SELECT count(*) from zip where zip > -1");

            ResultSet rs = sStatement.getResultSet();

            rs.next();
            System.out.println("count time (zip table) " + rs.getInt(1)
                               + " rows  -- " + sw.elapsedTime() + " ms");
        } catch (SQLException e) {}
    }
项目:dremio-oss    文件:TestInformationSchemaColumns.java   
@Test
public void test_DATETIME_PRECISION_hasINTERIMValue_mdrReqINTERVAL_2D_S5() throws SQLException {
  assertThat( "When DRILL-3244 fixed, un-ignore above method and purge this.",
              getIntOrNull( mdrReqINTERVAL_2D_S5, "DATETIME_PRECISION" ), equalTo( 2 ) );
}
项目:openjdk-jdk10    文件:StubSyncResolver.java   
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
项目:s-store    文件:JDBC4PreparedStatement.java   
protected synchronized void checkParameterBounds(int parameterIndex) throws SQLException
{
    checkClosed();
    if ((parameterIndex < 1) || (parameterIndex > this.Query.getParameterCount())) {
        throw SQLError.get(SQLError.PARAMETER_NOT_FOUND, parameterIndex, this.Query.getParameterCount());
    }
}
项目:the-vigilantes    文件:CallableStatementWrapper.java   
public void setCharacterStream(String parameterName, Reader reader, int length) throws SQLException {
    try {
        if (this.wrappedStmt != null) {
            ((CallableStatement) this.wrappedStmt).setCharacterStream(parameterName, reader, length);
        } else {
            throw SQLError.createSQLException("No operations allowed after statement closed", SQLError.SQL_STATE_GENERAL_ERROR, this.exceptionInterceptor);
        }
    } catch (SQLException sqlEx) {
        checkAndFireConnectionError(sqlEx);
    }
}
项目:BibliotecaPS    文件:JDBC4Connection.java   
public void setClientInfo(Properties properties) throws SQLClientInfoException {
    try {
        getClientInfoProviderImpl().setClientInfo(this, properties);
    } catch (SQLClientInfoException ciEx) {
        throw ciEx;
    } catch (SQLException sqlEx) {
        SQLClientInfoException clientInfoEx = new SQLClientInfoException();
        clientInfoEx.initCause(sqlEx);

        throw clientInfoEx;
    }
}
项目:tomcat7    文件:JDBCRealm.java   
/**
 * Prepare for the beginning of active use of the public methods of this
 * component and implement the requirements of
 * {@link org.apache.catalina.util.LifecycleBase#startInternal()}.
 *
 * @exception LifecycleException if this component detects a fatal error
 *  that prevents this component from being used
 */
@Override
protected void startInternal() throws LifecycleException {

    // Validate that we can open our connection - but let tomcat
    // startup in case the database is temporarily unavailable
    try {
        open();
    } catch (SQLException e) {
        containerLog.error(sm.getString("jdbcRealm.open"), e);
    }

    super.startInternal();
}
项目:tkcg    文件:DbDataMapHelper.java   
/**
 * Gets tables.
 *
 * @param connection the connection
 * @param keys keys
 * @param tablesOverride the tables override @return the tables
 * @throws SQLException the sql exception
 */
public Map<String, Map<String, Object>> getTables(Connection connection, String keys,
                                                  Map<String, Map<String, Object>> tablesOverride) throws SQLException {
    Map<String, Map<String, Object>> dataMap = new HashMap<>(16);
    DatabaseMetaData metaData = connection.getMetaData();
    // 处理key列表
    List<String> keyList = new ArrayList<>(1);
    if (keys != null) {
        String[] keyArray = keys.split(",");
        keyList = Arrays.asList(keyArray);
    } else {
        keyList.add("%");
    }
    // 根据key列表抽取指定表
    for (String key : keyList) {
        ResultSet resultSet = metaData.getTables(null, null, key, null);
        while (resultSet.next()) {
            Map<String, Object> table = new HashMap<>(4);
            String tableName = resultSet.getString(TABLE_NAME);
            LOGGER.info("抽取表结构>>{}", tableName);
            // 获取主键
            ResultSet primaryKeys = metaData.getPrimaryKeys(null, null, tableName);
            if (primaryKeys.next()) {
                String primaryColumn = primaryKeys.getString(COLUMN_NAME);
                table.put("primaryColumn", primaryColumn);
                table.put("primaryName", StringUtils.getCamelCaseString(primaryColumn, false));
                table.put("primaryAuto", false);
            } else {
                LOGGER.warn("获取表{}主键失败,跳过该表", tableName);
                continue;
            }
            table.put("tableName", tableName);
            table.put("comment", resultSet.getString(REMARKS));
            String className = StringUtils.getCamelCaseString(tableName, true);
            table.put("className", className);

            table.put("imports", new HashSet<>(5));

            // 使用配置文件进行覆盖
            Map<String, Object> tableOverride = tablesOverride.get(tableName);
            Map<String, Map<String, Object>> columnsOverride = new HashMap<>(0);
            if (tableOverride != null) {
                table.putAll(tableOverride);
                table.remove("columns");
                List<Map<String, Object>> columnsOverrideList = (List<Map<String, Object>>) tableOverride.get("columns");
                if (columnsOverrideList != null) {
                    columnsOverride = columnsOverrideList.stream().collect(Collectors.toMap(o -> (String) o.get("columnName"),
                                                                                            o -> o));
                }
            }
            List<Map<String, Object>> columns = getColumns(connection, table, columnsOverride);
            table.put("columns", columns);
            dataMap.put(tableName, table);
        }
    }
    return dataMap;
}
项目:incubator-netbeans    文件:CustomJDBCConnectionProvider.java   
@Override
public void stop() {
    if(connection != null) {
        try {
            connection.close();
        } catch (SQLException ex) {

        }
        connection = null;
    }
}
项目:incubator-netbeans    文件:DefaultAdaptor.java   
/**
* Are stored procedure calls using the stored procedure escape
* syntax supported?
* @return <code>true</code> if so
* @exception SQLException if a database access error occurs
*/
public boolean supportsStoredProcedures() throws SQLException
{
    Boolean storedProcedures = (Boolean)properties.get(PROP_STORED_PROCEDURES);
    if (storedProcedures == null) {
        if (dmd != null) storedProcedures = dmd.supportsStoredProcedures() ? Boolean.TRUE : Boolean.FALSE;
        else throw new SQLException(bundle.getString("EXC_NoDBMetadata")); // NOI18N
        properties.put(PROP_STORED_PROCEDURES, storedProcedures);
    }

    return storedProcedures.booleanValue();
}
项目:garlicts    文件:JdbcTemplate.java   
/**
 * 查询对应的实体列表,返回多条记录
 */
public <T> List<T> queryEntityList(Class<T> entityClass, String sql, Object... params) {
    List<T> result;
    try {
        result = queryRunner.query(sql, new BeanListHandler<T>(entityClass), params);
    } catch (SQLException e) {
        logger.error("查询出错!");
        throw new RuntimeException(e);
    }
    printSQL(sql);
    return result;
}
项目:the-vigilantes    文件:ConnectionRegressionTest.java   
public void testBug46637() throws Exception {
    String hostname = getPortFreeHostname(null, new NonRegisteringDriver());
    UnreliableSocketFactory.flushAllStaticData();
    UnreliableSocketFactory.downHost(hostname);

    try {
        Connection noConn = getConnectionWithProps("socketFactory=testsuite.UnreliableSocketFactory");
        noConn.close();
    } catch (SQLException sqlEx) {
        assertTrue(sqlEx.getMessage().indexOf("has not received") != -1);
    } finally {
        UnreliableSocketFactory.flushAllStaticData();
    }
}
项目:s-store    文件:JDBCPreparedStatement.java   
/**
 * Checks if the specified parameter index value is valid in terms of
 * getting an OUT or INOUT parameter value. <p>
 *
 * @param i The parameter index to check
 * @throws SQLException if the specified parameter index is invalid
 */
protected void checkGetParameterIndex(int i) throws SQLException {

    String msg;

    checkClosed();

    if (i < 1 || i > parameterValues.length) {
        msg = "parameter index out of range: " + i;

        throw Util.outOfRangeArgument(msg);
    }

    int mode = parameterModes[i - 1];

    switch (mode) {

        case SchemaObject.ParameterModes.PARAM_UNKNOWN :
        case SchemaObject.ParameterModes.PARAM_OUT :
        case SchemaObject.ParameterModes.PARAM_INOUT :
            break;
        case SchemaObject.ParameterModes.PARAM_IN :
        default :
            msg = "Not OUT or INOUT mode: " + mode + " for parameter: "
                  + i;

            throw Util.invalidArgument(msg);
    }
}
项目:tg-eventstore    文件:LegacyMysqlEventSource.java   
@Override
public void close() {
    try {
        dataSource.close();
    } catch (SQLException e) {
        LoggerFactory.getLogger(LegacyPooledMysqlEventSource.class).warn("Failed to close event source", e);
    }
}
项目:Progetto-N    文件:GuiSetSale.java   
public GuiSetSale() throws SQLException {
    initComponents();
    setLocationRelativeTo(null);
    fileChooser = new FileChooser();
    createDb = new CreateDb();
    guiInputSale = new GuiInputSale();
    createDb.createTableSale();
    imprevisto();
}
项目:osc-core    文件:ArchiveService.java   
private Query getCallableStatementTaskPredecessor(EntityManager em, Timestamp sqlTimeString, String dir) throws SQLException {
    File cvsFile = new File(dir + "task_predecessor.csv");
    Query spq = em.createNativeQuery("{CALL CSVWRITE(?, ?, ?)}");
    spq.setParameter(1, String.valueOf(cvsFile.getAbsoluteFile()));
    spq.setParameter(2, "SELECT * FROM TASK_PREDECESSOR WHERE task_id IN (SELECT ID FROM TASK WHERE job_fk IN (SELECT ID FROM JOB WHERE completed_timestamp <= '"+sqlTimeString+"'))");
    spq.setParameter(3,"charset=UTF-8 fieldSeparator=,");
    return spq;
}
项目:lams    文件:MysqlIO.java   
/**
 * Runs an 'EXPLAIN' on the given query and dumps the results to the log
 * 
 * @param querySQL
 * @param truncatedQuery
 * 
 * @throws SQLException
 */
protected void explainSlowQuery(byte[] querySQL, String truncatedQuery) throws SQLException {
    if (StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT)
            || (versionMeetsMinimum(5, 6, 3) && StringUtils.startsWithIgnoreCaseAndWs(truncatedQuery, EXPLAINABLE_STATEMENT_EXTENSION) != -1)) {

        PreparedStatement stmt = null;
        java.sql.ResultSet rs = null;

        try {
            stmt = (PreparedStatement) this.connection.clientPrepareStatement("EXPLAIN ?");
            stmt.setBytesNoEscapeNoQuotes(1, querySQL);
            rs = stmt.executeQuery();

            StringBuilder explainResults = new StringBuilder(Messages.getString("MysqlIO.8") + truncatedQuery + Messages.getString("MysqlIO.9"));

            ResultSetUtil.appendResultSetSlashGStyle(explainResults, rs);

            this.connection.getLog().logWarn(explainResults.toString());
        } catch (SQLException sqlEx) {
        } finally {
            if (rs != null) {
                rs.close();
            }

            if (stmt != null) {
                stmt.close();
            }
        }
    }
}
项目:QDrill    文件:DrillStatementImpl.java   
@Override
public boolean isClosed() {
  try {
    return super.isClosed();
  }
  catch ( SQLException e ) {
    // Currently can't happen, since AvaticaStatement.isClosed() never throws
    // SQLException.
    throw new DrillRuntimeException(
        "Unexpected exception from " + getClass().getSuperclass()
        + ".isClosed(): " + e,
        e );
  }
}
项目:sbc-qsystem    文件:ResultStateServices.java   
/**
 * Метод получения коннекта к базе если отчет строится через коннект. Если отчет строится не
 * через коннект, а формироватором, то выдать null.
 *
 * @return коннект соединения к базе или null.
 */
@Override
public Connection getConnection(String driverClassName, String url, String username,
    String password, HttpRequest request) {
    final Connection connection;
    try {
        Class.forName(driverClassName);
        connection = DriverManager.getConnection(url, username, password);
    } catch (SQLException | ClassNotFoundException ex) {
        throw new ReportException(ResultStateServices.class.getName() + " " + ex);
    }
    return connection;
}
项目:solo-spring    文件:JdbcTransaction.java   
/**
 * close the connection.
 */
public void dispose() {
    try {
        connection.close();

        JdbcRepository.TX.set(null);
    } catch (final SQLException e) {
        throw new RuntimeException("close connection", e);
    } finally {
        isActive = false;
        connection = null;
    }
}
项目:jdk8u-jdk    文件:SQLExceptionTests.java   
/**
 * Create SQLException with null Throwable
 */
@Test
public void test8() {
    SQLException ex = new SQLException((Throwable)null);
    assertTrue(ex.getMessage() == null
            && ex.getSQLState() == null
            && ex.getCause() == null
            && ex.getErrorCode() == 0);
}
项目:postguice    文件:SimpleStringUserType.java   
@Override
public Object nullSafeGet(final ResultSet rs, final String[] names, final SharedSessionContractImplementor session, final Object owner) throws HibernateException, SQLException {
    String value = rs.getString(names[0]);

    if (value == null) {
        return null;
    } else {
        return construct(value);
    }
}
项目:spanner-jdbc    文件:CloudSpannerPreparedStatementTest.java   
@Test()
public void testDeleteStatementWithNullValue() throws SQLException
{
    Mutations mutations = getMutations("DELETE FROM FOO WHERE ID IS NULL");
    Assert.assertEquals(DeleteWorker.class, mutations.getWorker().getClass());
    Assert.assertEquals("SELECT `FOO`.`ID` FROM `FOO` WHERE ID IS NULL",
            mutations.getWorker().select.toString());
}
项目:BibliotecaPS    文件:PreparedStatement.java   
/**
 * @param parameterIndex
 * @param parameterObj
 * @param targetSqlType
 * 
 * @throws SQLException
 */
public void setObject(int parameterIndex, Object parameterObj, int targetSqlType) throws SQLException {
    if (!(parameterObj instanceof BigDecimal)) {
        setObject(parameterIndex, parameterObj, targetSqlType, 0);
    } else {
        setObject(parameterIndex, parameterObj, targetSqlType, ((BigDecimal) parameterObj).scale());
    }
}
项目:tqdev-metrics    文件:DatabaseCachedAccess.java   
protected long queryLongWithParameter(String sql, String p1) {
    try {
        PreparedStatement statement = connection.prepareStatement(sql);
        statement.setString(1, p1);
        ResultSet rs = statement.executeQuery();
        if (!rs.next()) {
            return -1;
        }
        return rs.getInt(0);
    } catch (SQLException e) {
        return -1;
    }
}
项目:Machine-Learning-End-to-Endguide-for-Java-developers    文件:DatabaseExample.java   
public DatabaseExample() {
        try {
            Class.forName("com.mysql.jdbc.Driver");
            String url = "jdbc:mysql://localhost:3306/example";
            connection = DriverManager.getConnection(url, "root", "explore");

            // Needed to reset the contents of the table
            Statement statement = connection.createStatement();
            statement.execute("TRUNCATE URLTABLE;");

            String insertSQL = "INSERT INTO  `example`.`URLTABLE` "
                    + "(`url`) VALUES " + "(?);";
            PreparedStatement stmt = connection.prepareStatement(insertSQL);

            stmt.setString(1, "https://en.wikipedia.org/wiki/Data_science");
            stmt.execute();
            stmt.setString(1, "https://en.wikipedia.org/wiki/Bishop_Rock,_Isles_of_Scilly");
            stmt.execute();

//            String selectSQL = "select * from Record where URL = '" + url + "'";
            String selectSQL = "select * from URLTABLE";
            statement = connection.createStatement();
            ResultSet resultSet = statement.executeQuery(selectSQL);

            out.println("List of URLs");
            while (resultSet.next()) {
                out.println(resultSet.getString(2));
            } 
        } catch (SQLException | ClassNotFoundException ex) {
            ex.printStackTrace();
        }
    }
项目:mycat-src-1.6.1-RELEASE    文件:DataMigratorUtil.java   
public static long querySize(DataNode dn,String tableName) throws SQLException{
    List<Map<String, Object>> list=null;
    long size = 0L;
    Connection con = null;
    try {
        con =  getMysqlConnection(dn);
        list = executeQuery(con, "select count(1) size from "+tableName);
        size = (long) list.get(0).get("size");
    } catch (SQLException e) {
        throw e;
    }finally{
        JdbcUtils.close(con);
    }
    return size;
}
项目:dswork.jdbc    文件:StatementSpy.java   
public int getFetchDirection() throws SQLException
{
    return realStatement.getFetchDirection();
}
项目:openjdk-jdk10    文件:StubSyncResolver.java   
@Override
public float getFloat(String columnLabel) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}