Java Code Examples for java.sql.SQLException

The following are top voted examples for showing how to use java.sql.SQLException. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to generate more good examples.
Example 1
Project: parabuild-ci   File: TestCascade.java   View source code 9 votes vote down vote up
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();
    }
 
Example 2
Project: the-vigilantes   File: JDBC4ClientInfoProviderSP.java   View source code 7 votes vote down vote up
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;
    }
}
 
Example 3
Project: openjdk-jdk10   File: StubSyncResolver.java   View source code 6 votes vote down vote up
@Override
public void updateInt(String columnLabel, int x) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 4
Project: s-store   File: JDBC4PreparedStatement.java   View source code 6 votes vote down vote up
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());
    }
}
 
Example 5
Project: BibliotecaPS   File: JDBC4Connection.java   View source code 6 votes vote down vote up
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;
    }
}
 
Example 6
Project: plugin-bt-jira   File: JiraUpdateDaoTest.java   View source code 6 votes vote down vote up
/**
 * 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();
	}
}
 
Example 7
Project: spr   File: SqlDelete.java   View source code 6 votes vote down vote up
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();}
 }
 
Example 8
Project: BibliotecaPS   File: JDBC4ConnectionWrapper.java   View source code 6 votes vote down vote up
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;
        }
    }
}
 
Example 9
Project: the-vigilantes   File: CallableStatementWrapper.java   View source code 5 votes vote down vote up
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);
    }
}
 
Example 10
Project: tkcg   File: DbDataMapHelper.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 11
Project: incubator-netbeans   File: CustomJDBCConnectionProvider.java   View source code 5 votes vote down vote up
@Override
public void stop() {
    if(connection != null) {
        try {
            connection.close();
        } catch (SQLException ex) {
            
        }
        connection = null;
    }
}
 
Example 12
Project: incubator-netbeans   File: DefaultAdaptor.java   View source code 5 votes vote down vote up
/**
* 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();
}
 
Example 13
Project: garlicts   File: JdbcTemplate.java   View source code 5 votes vote down vote up
/**
 * 查询对应的实体列表,返回多条记录
 */
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;
}
 
Example 14
Project: the-vigilantes   File: ConnectionRegressionTest.java   View source code 5 votes vote down vote up
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();
    }
}
 
Example 15
Project: s-store   File: JDBCPreparedStatement.java   View source code 5 votes vote down vote up
/**
 * 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);
    }
}
 
Example 16
Project: tg-eventstore   File: LegacyMysqlEventSource.java   View source code 5 votes vote down vote up
@Override
public void close() {
    try {
        dataSource.close();
    } catch (SQLException e) {
        LoggerFactory.getLogger(LegacyPooledMysqlEventSource.class).warn("Failed to close event source", e);
    }
}
 
Example 17
Project: Progetto-N   File: GuiSetSale.java   View source code 5 votes vote down vote up
public GuiSetSale() throws SQLException {
    initComponents();
    setLocationRelativeTo(null);
    fileChooser = new FileChooser();
    createDb = new CreateDb();
    guiInputSale = new GuiInputSale();
    createDb.createTableSale();
    imprevisto();
}
 
Example 18
Project: osc-core   File: ArchiveService.java   View source code 5 votes vote down vote up
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;
}
 
Example 19
Project: lams   File: MysqlIO.java   View source code 5 votes vote down vote up
/**
 * 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();
            }
        }
    }
}
 
Example 20
Project: QDrill   File: DrillStatementImpl.java   View source code 5 votes vote down vote up
@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 );
  }
}
 
Example 21
Project: Nird2   File: JdbcDatabase.java   View source code 5 votes vote down vote up
@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);
	}
}
 
Example 22
Project: sbc-qsystem   File: ResultStateServices.java   View source code 5 votes vote down vote up
/**
 * Метод получения коннекта к базе если отчет строится через коннект. Если отчет строится не
 * через коннект, а формироватором, то выдать 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;
}
 
Example 23
Project: solo-spring   File: JdbcTransaction.java   View source code 5 votes vote down vote up
/**
 * 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;
	}
}
 
Example 24
Project: jdk8u-jdk   File: SQLExceptionTests.java   View source code 5 votes vote down vote up
/**
 * 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);
}
 
Example 25
Project: postguice   File: SimpleStringUserType.java   View source code 5 votes vote down vote up
@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);
	}
}
 
Example 26
Project: DMS   File: LoadGoingoutApplyStatus.java   View source code 5 votes vote down vote up
@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;
	}
}
 
Example 27
Project: spanner-jdbc   File: CloudSpannerPreparedStatementTest.java   View source code 5 votes vote down vote up
@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());
}
 
Example 28
Project: BibliotecaPS   File: PreparedStatement.java   View source code 5 votes vote down vote up
/**
 * @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());
    }
}
 
Example 29
Project: hotelbook-JavaWeb   File: FloorInfoServiceImpl.java   View source code 5 votes vote down vote up
@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;
    }
}
 
Example 30
Project: tqdev-metrics   File: DatabaseCachedAccess.java   View source code 5 votes vote down vote up
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;
	}
}
 
Example 31
Project: incubator-netbeans   File: QueryBuilderMetaData.java   View source code 5 votes vote down vote up
/**
 * 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;
}
 
Example 32
Project: Machine-Learning-End-to-Endguide-for-Java-developers   File: DatabaseExample.java   View source code 5 votes vote down vote up
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();
        }
    }
 
Example 33
Project: mycat-src-1.6.1-RELEASE   File: DataMigratorUtil.java   View source code 5 votes vote down vote up
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;
}
 
Example 34
Project: HueSense   File: PresenceSensor.java   View source code 5 votes vote down vote up
@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;
}
 
Example 35
Project: parabuild-ci   File: TestCacheSize.java   View source code 4 votes vote down vote up
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) {}
    }
 
Example 36
Project: dswork.jdbc   File: StatementSpy.java   View source code 4 votes vote down vote up
public int getFetchDirection() throws SQLException
{
	return realStatement.getFetchDirection();
}
 
Example 37
Project: openjdk-jdk10   File: StubSyncResolver.java   View source code 4 votes vote down vote up
@Override
public float getFloat(String columnLabel) throws SQLException {
    throw new UnsupportedOperationException("Not supported yet.");
}
 
Example 38
Project: dremio-oss   File: TestInformationSchemaColumns.java   View source code 4 votes vote down vote up
@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 ) );
}
 
Example 39
Project: mycat-src-1.6.1-RELEASE   File: MongoResultSet.java   View source code 4 votes vote down vote up
@Override
public byte getByte(String columnLabel) throws SQLException {
	
	return getNumber(columnLabel).byteValue();
}
 
Example 40
Project: calcite-avatica   File: AvaticaNoopResultSet.java   View source code 4 votes vote down vote up
@Override public Ref getRef(int columnIndex) throws SQLException {
  throw unsupported();
}