Java Code Examples for java.sql.Types

The following are top voted examples for showing how to use java.sql.Types. 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: lams   File: SQLServerDialect.java   View source code 8 votes vote down vote up
/**
 * Constructs a SQLServerDialect
 */
public SQLServerDialect() {
	registerColumnType( Types.VARBINARY, "image" );
	registerColumnType( Types.VARBINARY, 8000, "varbinary($l)" );
	registerColumnType( Types.LONGVARBINARY, "image" );
	registerColumnType( Types.LONGVARCHAR, "text" );
	registerColumnType( Types.BOOLEAN, "bit" );

	registerFunction( "second", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(second, ?1)" ) );
	registerFunction( "minute", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(minute, ?1)" ) );
	registerFunction( "hour", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(hour, ?1)" ) );
	registerFunction( "locate", new StandardSQLFunction( "charindex", StandardBasicTypes.INTEGER ) );

	registerFunction( "extract", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datepart(?1, ?3)" ) );
	registerFunction( "mod", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "?1 % ?2" ) );
	registerFunction( "bit_length", new SQLFunctionTemplate( StandardBasicTypes.INTEGER, "datalength(?1) * 8" ) );

	registerFunction( "trim", new AnsiTrimEmulationFunction() );

	registerKeyword( "top" );
}
 
Example 2
Project: the-vigilantes   File: CallableStatementRegressionTest.java   View source code 8 votes vote down vote up
public void testBug35199() throws Exception {
    if (!versionMeetsMinimum(5, 0)) {
        return;
    }

    createFunction("test_function", "(a varchar(40), b bigint(20), c varchar(80)) RETURNS bigint(20) LANGUAGE SQL DETERMINISTIC "
            + "MODIFIES SQL DATA COMMENT 'bbb' BEGIN RETURN 1; END; ");

    CallableStatement callable = null;
    try {
        callable = this.conn.prepareCall("{? = call test_function(?,101,?)}");
        callable.registerOutParameter(1, Types.BIGINT);

        callable.setString(2, "FOO");
        callable.setString(3, "BAR");
        callable.executeUpdate();
    } finally {
        if (callable != null) {
            callable.close();
        }
    }
}
 
Example 3
Project: ProyectoPacientes   File: ServerPreparedStatement.java   View source code 7 votes vote down vote up
/**
 * @see java.sql.PreparedStatement#setBinaryStream(int, java.io.InputStream, int)
 */
@Override
public void setBinaryStream(int parameterIndex, InputStream x, int length) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {

        if (x == null) {
            setNull(parameterIndex, java.sql.Types.BINARY);
        } else {
            BindValue binding = getBinding(parameterIndex, true);
            resetToType(binding, MysqlDefs.FIELD_TYPE_BLOB);

            binding.value = x;
            binding.isLongData = true;

            if (this.connection.getUseStreamLengthsInPrepStmts()) {
                binding.bindLength = length;
            } else {
                binding.bindLength = -1;
            }
        }
    }
}
 
Example 4
Project: lams   File: ServerPreparedStatement.java   View source code 7 votes vote down vote up
/**
 * @see java.sql.PreparedStatement#setCharacterStream(int, java.io.Reader, int)
 */
@Override
public void setCharacterStream(int parameterIndex, Reader reader, int length) throws SQLException {
    synchronized (checkClosed().getConnectionMutex()) {

        if (reader == null) {
            setNull(parameterIndex, java.sql.Types.BINARY);
        } else {
            BindValue binding = getBinding(parameterIndex, true);
            setType(binding, MysqlDefs.FIELD_TYPE_BLOB);

            binding.value = reader;
            binding.isNull = false;
            binding.isLongData = true;

            if (this.connection.getUseStreamLengthsInPrepStmts()) {
                binding.bindLength = length;
            } else {
                binding.bindLength = -1;
            }
        }
    }
}
 
Example 5
Project: lams   File: MultipleHiLoPerTableGenerator.java   View source code 7 votes vote down vote up
public String[] sqlCreateStrings(Dialect dialect) throws HibernateException {
	return new String[] {
		new StringBuilder( dialect.getCreateTableString() )
				.append( ' ' )
				.append( tableName )
				.append( " ( " )
				.append( pkColumnName )
				.append( ' ' )
				.append( dialect.getTypeName( Types.VARCHAR, keySize, 0, 0 ) )
				.append( ",  " )
				.append( valueColumnName )
				.append( ' ' )
				.append( dialect.getTypeName( Types.INTEGER ) )
				.append( " )" )
				.append( dialect.getTableTypeString() )
				.toString()
	};
}
 
Example 6
Project: aliyun-maxcompute-data-collectors   File: HCatalogExportTest.java   View source code 7 votes vote down vote up
/**
 * Test other file formats.
 */
public void testSequenceFile() throws Exception {
  final int TOTAL_RECORDS = 1 * 10;
  String table = getTableName().toUpperCase();
  ColumnGenerator[] cols = new ColumnGenerator[] {
      HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(0),
          "varchar(20)", Types.VARCHAR, HCatFieldSchema.Type.STRING, 0, 0,
          "1", "1", KeyType.STATIC_KEY),
      HCatalogTestUtils.colGenerator(HCatalogTestUtils.forIdx(1),
          "varchar(20)", Types.VARCHAR, HCatFieldSchema.Type.STRING, 0, 0,
          "2", "2", KeyType.DYNAMIC_KEY), };

  List<String> addlArgsArray = new ArrayList<String>();
  addlArgsArray.add("--hive-partition-key");
  addlArgsArray.add("col0");
  addlArgsArray.add("--hive-partition-value");
  addlArgsArray.add("1");
  utils.setStorageInfo(HCatalogTestUtils.STORED_AS_SEQFILE);
  runHCatExport(addlArgsArray, TOTAL_RECORDS, table, cols);
}
 
Example 7
Project: the-vigilantes   File: PreparedStatement.java   View source code 6 votes vote down vote up
/**
 * Set a parameter to a java.sql.Time value. The driver converts this to a
 * SQL TIME value when it sends it to the database, using the given
 * timezone.
 * 
 * @param parameterIndex
 *            the first parameter is 1...));
 * @param x
 *            the parameter value
 * @param tz
 *            the timezone to use
 * 
 * @throws java.sql.SQLException
 *             if a database access error occurs
 */
private void setTimeInternal(int parameterIndex, Time x, Calendar targetCalendar, TimeZone tz, boolean rollForward) throws java.sql.SQLException {
    if (x == null) {
        setNull(parameterIndex, java.sql.Types.TIME);
    } else {
        checkClosed();

        if (!this.useLegacyDatetimeCode) {
            newSetTimeInternal(parameterIndex, x, targetCalendar);
        } else {
            Calendar sessionCalendar = getCalendarInstanceForSessionOrNew();

            x = TimeUtil.changeTimezone(this.connection, sessionCalendar, targetCalendar, x, tz, this.connection.getServerTimezoneTZ(), rollForward);

            setInternal(parameterIndex, "'" + x.toString() + "'");
        }

        this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.TIME;
    }
}
 
Example 8
Project: OpenVertretung   File: ResultSetMetaData.java   View source code 6 votes vote down vote up
/**
 * Checks if the SQL Type is a Decimal/Number Type
 * 
 * @param type
 *            SQL Type
 */
private static final boolean isDecimalType(int type) {
    switch (type) {
        case Types.BIT:
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
        case Types.NUMERIC:
        case Types.DECIMAL:
            return true;
    }

    return false;
}
 
Example 9
Project: the-vigilantes   File: ResultSetMetaData.java   View source code 6 votes vote down vote up
/**
 * Checks if the SQL Type is a Decimal/Number Type
 * 
 * @param type
 *            SQL Type
 */
private static final boolean isDecimalType(int type) {
    switch (type) {
        case Types.BIT:
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
        case Types.NUMERIC:
        case Types.DECIMAL:
            return true;
    }

    return false;
}
 
Example 10
Project: mybatis-generator-extension   File: CustomJavaTypeResolver.java   View source code 6 votes vote down vote up
public CustomJavaTypeResolver() {
    super();
    typeMap.put(Types.ARRAY, new JdbcTypeInformation("ARRAY", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.BIGINT, new JdbcTypeInformation("BIGINT", new FullyQualifiedJavaType(Long.class.getName())));
    typeMap.put(Types.BINARY, new JdbcTypeInformation("BINARY", new FullyQualifiedJavaType("byte[]")));
    typeMap.put(Types.BIT, new JdbcTypeInformation("BIT", new FullyQualifiedJavaType(Boolean.class.getName())));
    typeMap.put(Types.BLOB, new JdbcTypeInformation("BLOB", new FullyQualifiedJavaType("byte[]")));
    typeMap.put(Types.BOOLEAN, new JdbcTypeInformation("BOOLEAN", new FullyQualifiedJavaType(Boolean.class.getName())));
    typeMap.put(Types.CHAR, new JdbcTypeInformation("CHAR", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.CLOB, new JdbcTypeInformation("CLOB", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.DATALINK, new JdbcTypeInformation("DATALINK", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.DATE, new JdbcTypeInformation("DATE", new FullyQualifiedJavaType(Date.class.getName())));
    typeMap.put(Types.DECIMAL, new JdbcTypeInformation("DECIMAL", new FullyQualifiedJavaType(BigDecimal.class.getName())));
    typeMap.put(Types.DISTINCT, new JdbcTypeInformation("DISTINCT", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.DOUBLE, new JdbcTypeInformation("DOUBLE", new FullyQualifiedJavaType(Double.class.getName())));
    typeMap.put(Types.FLOAT, new JdbcTypeInformation("FLOAT", new FullyQualifiedJavaType(Double.class.getName())));
    typeMap.put(Types.INTEGER, new JdbcTypeInformation("INTEGER", new FullyQualifiedJavaType(Integer.class.getName())));
    typeMap.put(Types.JAVA_OBJECT, new JdbcTypeInformation("JAVA_OBJECT", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.LONGNVARCHAR, new JdbcTypeInformation("LONGNVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.LONGVARBINARY, new JdbcTypeInformation("LONGVARBINARY", new FullyQualifiedJavaType("byte[]")));
    typeMap.put(Types.LONGVARCHAR, new JdbcTypeInformation("LONGVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.NCHAR, new JdbcTypeInformation("NCHAR", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.NCLOB, new JdbcTypeInformation("NCLOB", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.NVARCHAR, new JdbcTypeInformation("NVARCHAR", new FullyQualifiedJavaType(String.class.getName())));
    typeMap.put(Types.NULL, new JdbcTypeInformation("NULL", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.NUMERIC, new JdbcTypeInformation("NUMERIC", new FullyQualifiedJavaType(BigDecimal.class.getName())));
    typeMap.put(Types.OTHER, new JdbcTypeInformation("OTHER", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.REAL, new JdbcTypeInformation("REAL", new FullyQualifiedJavaType(Float.class.getName())));
    typeMap.put(Types.REF, new JdbcTypeInformation("REF", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.SMALLINT, new JdbcTypeInformation("SMALLINT", new FullyQualifiedJavaType(Short.class.getName())));
    typeMap.put(Types.STRUCT, new JdbcTypeInformation("STRUCT", new FullyQualifiedJavaType(Object.class.getName())));
    typeMap.put(Types.TIME, new JdbcTypeInformation("TIME", new FullyQualifiedJavaType(Date.class.getName())));
    typeMap.put(Types.TIMESTAMP, new JdbcTypeInformation("TIMESTAMP", new FullyQualifiedJavaType(Date.class.getName())));
    // 更改默认的 Byte 为 Integer
    typeMap.put(Types.TINYINT, new JdbcTypeInformation("TINYINT", new FullyQualifiedJavaType(Integer.class.getName())));
    typeMap.put(Types.VARBINARY, new JdbcTypeInformation("VARBINARY", new FullyQualifiedJavaType("byte[]")));
    typeMap.put(Types.VARCHAR, new JdbcTypeInformation("VARCHAR", new FullyQualifiedJavaType(String.class.getName())));
}
 
Example 11
Project: traccar-service   File: QueryBuilder.java   View source code 6 votes vote down vote up
public QueryBuilder setDate(String name, Date value) throws SQLException {
    for (int i : indexes(name)) {
        try {
            if (value == null) {
                statement.setNull(i, Types.TIMESTAMP);
            } else {
                statement.setTimestamp(i, new Timestamp(value.getTime()));
            }
        } catch (SQLException error) {
            statement.close();
            connection.close();
            throw error;
        }
    }
    return this;
}
 
Example 12
Project: the-vigilantes   File: Field.java   View source code 6 votes vote down vote up
/**
 * Used by prepared statements to re-use result set data conversion methods
 * when generating bound parmeter retrieval instance for statement
 * interceptors.
 * 
 * @param tableName
 *            not used
 * @param columnName
 *            not used
 * @param charsetIndex
 *            the MySQL collation/character set index
 * @param jdbcType
 *            from java.sql.Types
 * @param length
 *            length in characters or bytes (for BINARY data).
 */
Field(String tableName, String columnName, int charsetIndex, int jdbcType, int length) {
    this.tableName = tableName;
    this.name = columnName;
    this.length = length;
    this.sqlType = jdbcType;
    this.colFlag = 0;
    this.colDecimals = 0;
    this.collationIndex = charsetIndex;
    this.valueNeedsQuoting = determineNeedsQuoting();

    switch (this.sqlType) {
        case Types.BINARY:
        case Types.VARBINARY:
            this.colFlag |= 128;
            this.colFlag |= 16;
            break;
    }
}
 
Example 13
Project: mark-mybatis-generator   File: DB2JavaTypeResolver.java   View source code 6 votes vote down vote up
public String calculateJdbcTypeName(IntrospectedColumn introspectedColumn) {
	String answer;
	JdbcTypeInformation jdbcTypeInformation = typeMap
			.get(introspectedColumn.getJdbcType());

	if (jdbcTypeInformation == null) {
		switch (introspectedColumn.getJdbcType()) {
		case Types.DECIMAL:
			answer = "DECIMAL"; //$NON-NLS-1$
			break;
		case Types.NUMERIC:
			answer = "NUMERIC"; //$NON-NLS-1$
			break;
		default:
			answer = null;
			break;
		}
	} else {
		answer = jdbcTypeInformation.getJdbcTypeName();
	}

	return answer;
}
 
Example 14
Project: lams   File: PreparedStatement.java   View source code 6 votes vote down vote up
/**
 * Set a parameter to a java.sql.Date value. The driver converts this to a
 * SQL DATE value when it sends it to the database.
 * 
 * @param parameterIndex
 *            the first parameter is 1, the second is 2, ...
 * @param x
 *            the parameter value
 * @param cal
 *            the calendar to interpret the date with
 * 
 * @exception SQLException
 *                if a database-access error occurs.
 */
public void setDate(int parameterIndex, java.sql.Date x, Calendar cal) throws SQLException {
    if (x == null) {
        setNull(parameterIndex, java.sql.Types.DATE);
    } else {
        if (!this.useLegacyDatetimeCode) {
            newSetDateInternal(parameterIndex, x, cal);
        } else {
            synchronized (checkClosed().getConnectionMutex()) {
                if (this.ddf == null) {
                    this.ddf = new SimpleDateFormat("''yyyy-MM-dd''", Locale.US);
                }
                if (cal != null) {
                    this.ddf.setTimeZone(cal.getTimeZone());
                }

                setInternal(parameterIndex, this.ddf.format(x));

                this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.DATE;
            }
        }
    }
}
 
Example 15
Project: uroborosql   File: SqlAgentTest.java   View source code 6 votes vote down vote up
/**
 * DB更新処理のテストケース。
 */
@Test
public void testExecuteUpdate() throws Exception {
	// 事前条件
	cleanInsert(Paths.get("src/test/resources/data/setup", "testExecuteUpdate.ltsv"));

	SqlContext ctx = agent.contextFrom("example/selectinsert_product")
			.param("product_id", new BigDecimal("0"), JDBCType.DECIMAL)
			.param("jan_code", "1234567890123", Types.CHAR);

	int updateCount = agent.update(ctx);
	assertEquals("データの登録に失敗しました。", 1, updateCount);

	// 検証処理
	List<Map<String, Object>> expectedDataList = getDataFromFile(Paths.get(
			"src/test/resources/data/expected/SqlAgent", "testExecuteUpdate.ltsv"));
	List<Map<String, Object>> actualDataList = agent.query("example/select_product")
			.paramList("product_id", 0, 1).stream(new MapResultSetConverter(CaseFormat.LOWER_SNAKE_CASE))
			.collect(Collectors.toList());

	assertEquals(expectedDataList.toString(), actualDataList.toString());
}
 
Example 16
Project: the-vigilantes   File: CallableStatementRegressionTest.java   View source code 6 votes vote down vote up
/**
 * Tests fix for BUG#17898 - registerOutParameter not working when some
 * parameters pre-populated. Still waiting for feedback from JDBC experts
 * group to determine what correct parameter count from getMetaData() should
 * be, however.
 * 
 * @throws Exception
 *             if the test fails
 */
public void testBug17898() throws Exception {
    if (!serverSupportsStoredProcedures()) {
        return;
    }

    createProcedure("testBug17898", "(param1 VARCHAR(50), OUT param2 INT)\nBEGIN\nDECLARE rtn INT;\n" + "SELECT 1 INTO rtn;\nSET param2=rtn;\nEND");

    CallableStatement cstmt = this.conn.prepareCall("{CALL testBug17898('foo', ?)}");
    cstmt.registerOutParameter(1, Types.INTEGER);
    cstmt.execute();
    assertEquals(1, cstmt.getInt(1));

    cstmt.clearParameters();
    cstmt.registerOutParameter("param2", Types.INTEGER);
    cstmt.execute();
    assertEquals(1, cstmt.getInt(1));
}
 
Example 17
Project: BibliotecaPS   File: PreparedStatement.java   View source code 6 votes vote down vote up
/**
 * Sets the value for the placeholder as a serialized Java object (used by
 * various forms of setObject()
 * 
 * @param parameterIndex
 * @param parameterObj
 * 
 * @throws SQLException
 */
private final void setSerializableObject(int parameterIndex, Object parameterObj) throws SQLException {
    try {
        ByteArrayOutputStream bytesOut = new ByteArrayOutputStream();
        ObjectOutputStream objectOut = new ObjectOutputStream(bytesOut);
        objectOut.writeObject(parameterObj);
        objectOut.flush();
        objectOut.close();
        bytesOut.flush();
        bytesOut.close();

        byte[] buf = bytesOut.toByteArray();
        ByteArrayInputStream bytesIn = new ByteArrayInputStream(buf);
        setBinaryStream(parameterIndex, bytesIn, buf.length);
        this.parameterTypes[parameterIndex - 1 + getParameterIndexOffset()] = Types.BINARY;
    } catch (Exception ex) {
        SQLException sqlEx = SQLError.createSQLException(Messages.getString("PreparedStatement.54") + ex.getClass().getName(),
                SQLError.SQL_STATE_ILLEGAL_ARGUMENT, getExceptionInterceptor());
        sqlEx.initCause(ex);

        throw sqlEx;
    }
}
 
Example 18
Project: WeatherSystem   File: RegionDao.java   View source code 6 votes vote down vote up
/**
 * 分页返回城市信息
 * @param pageNum
 * @return
 */
public Page<Region> findPage(int pageNum){
    Page<Region> page = new Page <Region>();

    Object[] params = new Object[]{(pageNum - 1) * page.getPageSize(), page.getPageSize()};
    int[] types = new int[]{Types.INTEGER, Types.INTEGER};
    List<Region> regions = this.jdbcTemplate.query(SQL_FIND_PAGE_REGION, params, types, new RegionRowMapper());

    page.setList(regions);
    page.setCurrentPage(pageNum);
    page.setCurrentSize(regions.size());

    int itemCount = count();
    page.setTotalCount(itemCount);
    page.setTotalPage(itemCount / page.getPageSize() + 1);

    return page;
}
 
Example 19
Project: OpenVertretung   File: DatabaseMetaData.java   View source code 6 votes vote down vote up
static java.sql.ResultSet buildResultSet(com.mysql.jdbc.Field[] fields, java.util.ArrayList<ResultSetRow> rows, MySQLConnection c) throws SQLException {
    int fieldsLength = fields.length;

    for (int i = 0; i < fieldsLength; i++) {
        int jdbcType = fields[i].getSQLType();

        switch (jdbcType) {
            case Types.CHAR:
            case Types.VARCHAR:
            case Types.LONGVARCHAR:
                fields[i].setEncoding(c.getCharacterSetMetadata(), c);
                break;
            default:
                // do nothing
        }

        fields[i].setConnection(c);
        fields[i].setUseOldNameMetadata(true);
    }

    return com.mysql.jdbc.ResultSetImpl.getInstance(c.getCatalog(), fields, new RowDataStatic(rows), c, null, false);
}
 
Example 20
Project: OpenDiabetes   File: InformixTransferHelper.java   View source code 6 votes vote down vote up
int convertFromType(int type) {

        //Correct a bug in Informix JDBC driver that maps:
        // DATETIME YEAR TO FRACTION to TIME and
        // DATETIME HOUR TO SECOND to TIMESTAMP
        if (type == Types.TIMESTAMP) {
            type = Types.TIME;

            tracer.trace("Converted INFORMIX TIMESTAMP to TIME");
        } else if (type == Types.TIME) {
            type = Types.TIMESTAMP;

            tracer.trace("Converted INFORMIX TIME to TIMESTAMP");
        }

        return (type);
    }
 
Example 21
Project: NICON   File: VeiculoDao.java   View source code 6 votes vote down vote up
public String registrarVeiculo(Veiculo veiculo,String idContradto)
{
    System.out.println(veiculo.toString());
    String user =((Funcionario)SessionUtil.obterValor("utilizador")).getId().toString();
     String functionName = "FUNC_REGOBJ_VEICULO";
     Object resp = Call.callSampleFunction(functionName, Types.VARCHAR, 
                                            Integer.valueOf(SessionUtil.getUserlogado().getId().toString()),
                                            idContradto,
                                            veiculo.getNumeroMatricula(),
                                            veiculo.getMarca(),
                                            veiculo.getModelo(),
                                            ((veiculo.getNumMotor()==null || veiculo.getNumMotor().equals(""))? null : veiculo.getNumMotor()),
                                            veiculo.getChassi(),
                                            ((veiculo.getAnoFabrico()==null || veiculo.getAnoFabrico().equals(""))? null: veiculo.getAnoFabrico()),
                                            ((veiculo.getAnoCompra()==null || veiculo.getAnoCompra().equals(""))? null:veiculo.getAnoCompra()),
                                            veiculo.getCapacidade(),
                                            ((veiculo.getValorCompra()==null || veiculo.getValorCompra().equals(""))? null: Float.valueOf(veiculo.getValorCompra())),
                                            ((veiculo.getValorAtual()==null || veiculo.getValorAtual().equals("")) ? null : Float.valueOf(veiculo.getValorAtual())),
                                            ((veiculo.getTipoCobertura()==null || veiculo.getTipoCobertura().equals(""))? null : Integer.valueOf(veiculo.getTipoCobertura())),
                                            ((veiculo.getValorPremio() == null || veiculo.getValorPremio().equals(""))? null : Float.valueOf(veiculo.getValorPremio())),
                                            ((veiculo.getLimiteResp().equals("Ilimitado") ? null : Float.parseFloat(veiculo.getLimiteResp()))),
                                            veiculo.getCertificado()
                                                    );
return resp.toString();
}
 
Example 22
Project: parabuild-ci   File: InformixTransferHelper.java   View source code 6 votes vote down vote up
int convertToType(int type) {

        //Correct a bug in Informix JDBC driver that maps:
        // DATETIME YEAR TO FRACTION to TIME and
        // DATETIME HOUR TO SECOND to TIMESTAMP
        if (type == Types.TIMESTAMP) {
            type = Types.TIME;

            tracer.trace("Converted TIMESTAMP to INFORMIX TIME");
        } else if (type == Types.TIME) {
            type = Types.TIMESTAMP;

            tracer.trace("Converted TIME to INFORMIX TIMESTAMP");
        }

        return (type);
    }
 
Example 23
Project: OpenVertretung   File: DatabaseMetaData.java   View source code 6 votes vote down vote up
protected Field[] createFkMetadataFields() {
    Field[] fields = new Field[14];
    fields[0] = new Field("", "PKTABLE_CAT", Types.CHAR, 255);
    fields[1] = new Field("", "PKTABLE_SCHEM", Types.CHAR, 0);
    fields[2] = new Field("", "PKTABLE_NAME", Types.CHAR, 255);
    fields[3] = new Field("", "PKCOLUMN_NAME", Types.CHAR, 32);
    fields[4] = new Field("", "FKTABLE_CAT", Types.CHAR, 255);
    fields[5] = new Field("", "FKTABLE_SCHEM", Types.CHAR, 0);
    fields[6] = new Field("", "FKTABLE_NAME", Types.CHAR, 255);
    fields[7] = new Field("", "FKCOLUMN_NAME", Types.CHAR, 32);
    fields[8] = new Field("", "KEY_SEQ", Types.SMALLINT, 2);
    fields[9] = new Field("", "UPDATE_RULE", Types.SMALLINT, 2);
    fields[10] = new Field("", "DELETE_RULE", Types.SMALLINT, 2);
    fields[11] = new Field("", "FK_NAME", Types.CHAR, 0);
    fields[12] = new Field("", "PK_NAME", Types.CHAR, 0);
    fields[13] = new Field("", "DEFERRABILITY", Types.SMALLINT, 2);
    return fields;
}
 
Example 24
Project: ProyectoPacientes   File: Field.java   View source code 6 votes vote down vote up
/**
 * Used by prepared statements to re-use result set data conversion methods
 * when generating bound parmeter retrieval instance for statement
 * interceptors.
 * 
 * @param tableName
 *            not used
 * @param columnName
 *            not used
 * @param charsetIndex
 *            the MySQL collation/character set index
 * @param jdbcType
 *            from java.sql.Types
 * @param length
 *            length in characters or bytes (for BINARY data).
 */
Field(String tableName, String columnName, int charsetIndex, int jdbcType, int length) {
    this.tableName = tableName;
    this.name = columnName;
    this.length = length;
    this.sqlType = jdbcType;
    this.colFlag = 0;
    this.colDecimals = 0;
    this.collationIndex = charsetIndex;
    this.valueNeedsQuoting = determineNeedsQuoting();

    switch (this.sqlType) {
        case Types.BINARY:
        case Types.VARBINARY:
            this.colFlag |= 128;
            this.colFlag |= 16;
            break;
    }
}
 
Example 25
Project: lams   File: InterbaseDialect.java   View source code 6 votes vote down vote up
/**
 * Constructs a InterbaseDialect
 */
public InterbaseDialect() {
	super();
	registerColumnType( Types.BIT, "smallint" );
	registerColumnType( Types.BIGINT, "numeric(18,0)" );
	registerColumnType( Types.SMALLINT, "smallint" );
	registerColumnType( Types.TINYINT, "smallint" );
	registerColumnType( Types.INTEGER, "integer" );
	registerColumnType( Types.CHAR, "char(1)" );
	registerColumnType( Types.VARCHAR, "varchar($l)" );
	registerColumnType( Types.FLOAT, "float" );
	registerColumnType( Types.DOUBLE, "double precision" );
	registerColumnType( Types.DATE, "date" );
	registerColumnType( Types.TIME, "time" );
	registerColumnType( Types.TIMESTAMP, "timestamp" );
	registerColumnType( Types.VARBINARY, "blob" );
	registerColumnType( Types.NUMERIC, "numeric($p,$s)" );
	registerColumnType( Types.BLOB, "blob" );
	registerColumnType( Types.CLOB, "blob sub_type 1" );
	registerColumnType( Types.BOOLEAN, "smallint" );
	
	registerFunction( "concat", new VarArgsSQLFunction( StandardBasicTypes.STRING, "(","||",")" ) );
	registerFunction( "current_date", new NoArgSQLFunction( "current_date", StandardBasicTypes.DATE, false ) );

	getDefaultProperties().setProperty( Environment.STATEMENT_BATCH_SIZE, NO_BATCH );
}
 
Example 26
Project: hibernate-types   File: PostgreSQLEnumType.java   View source code 5 votes vote down vote up
public void nullSafeSet(
        PreparedStatement st,
        Object value,
        int index,
        SessionImplementor session)
        throws HibernateException, SQLException {
    if (value == null) {
        st.setNull(index, Types.OTHER);
    } else {
        st.setObject(index, value.toString(), Types.OTHER);
    }
}
 
Example 27
Project: NICON   File: RouboDao.java   View source code 5 votes vote down vote up
public String regRoubo(String idContrato,int quantidade, String modelo, float valor,String descricao )
{
   Conexao conexao = new Conexao();
   String idUser = ((Funcionario) SessionUtil.obterValor("utilizador")).getId().toString();
   int user = Integer.valueOf(idUser);
   if(conexao.getCon() != null)
   {
       resultado = (String) Call.callSampleFunction("FUNC_REGOBJ_ROUBO",Types.VARCHAR,user,idContrato,quantidade,modelo,valor,descricao );
   }
   return resultado;
}
 
Example 28
Project: ats-framework   File: SQLServerDbWriteAccess.java   View source code 5 votes vote down vote up
/**
 * Clear all meta info about an existing test scenario. Intended to be
 * called prior to adding meta data about a scenario.
 *
 * @param scenarioId
 * @param closeConnection
 * @throws DatabaseAccessException
 */
public void clearScenarioMetainfo(
                                   int scenarioId,
                                   boolean closeConnection ) throws DatabaseAccessException {

    final String errMsg = "Unable to clear scenario meta info for scenario with id " + scenarioId;

    final int indexRowsDeleted = 2;

    CallableStatement callableStatement = null;
    try {
        refreshInternalConnection();

        callableStatement = connection.prepareCall("{ call sp_clear_scenario_metainfo(?, ?) }");
        callableStatement.setInt(1, scenarioId);
        callableStatement.registerOutParameter(indexRowsDeleted, Types.INTEGER);

        callableStatement.execute();
    } catch (Exception e) {
        throw new DatabaseAccessException(errMsg, e);
    } finally {
        if (closeConnection) {
            DbUtils.close(connection, callableStatement);
        } else {
            DbUtils.closeStatement(callableStatement);
        }
    }
}
 
Example 29
Project: AdamantineShield   File: InventoryQueueEntry.java   View source code 5 votes vote down vote up
@Override
public void writeToConnection(Connection c) throws SQLException {
	Location<World> loc = carrier.getLocation();
	
	PreparedStatement ps = c.prepareStatement(QUERY);
	ps.setInt(1, loc.getBlockX());
	ps.setInt(2, loc.getBlockY());
	ps.setInt(3, loc.getBlockZ());
	ps.setInt(4, Database.worldCache.getDataId(c, carrier.getWorld().getUniqueId().toString()));
	ps.setByte(5, (byte) type.ordinal());
	ps.setInt(6, slot);
	ps.setInt(7, Database.causeCache.getDataId(c, cause.getUniqueId().toString()));
	ps.setInt(8, Database.idCache.getDataId(c, item.getType().getId()));
	ps.setByte(9, (byte) item.getCount());
	
	ps.setNull(10, Types.VARCHAR);
	try {
		String data = DataUtils.dataToString(item.toContainer());
		if (data != null)
			ps.setString(10, data);
	} catch (IOException e) {
		e.printStackTrace();
	}
	
	ps.setLong(11, timestamp);
	ps.executeUpdate();
}
 
Example 30
Project: org.mybatis.generator.core-1.3.5   File: JavaTypeResolverDefaultImpl.java   View source code 5 votes vote down vote up
protected FullyQualifiedJavaType overrideDefaultType(IntrospectedColumn column, FullyQualifiedJavaType defaultType) {
    FullyQualifiedJavaType answer = defaultType;
    
    switch (column.getJdbcType()) {
    case Types.BIT:
        answer = calculateBitReplacement(column, defaultType);
        break;
    case Types.DECIMAL:
    case Types.NUMERIC:
        answer = calculateBigDecimalReplacement(column, defaultType);
        break;
    }

    return answer;
}
 
Example 31
Project: OpenVertretung   File: StatementRegressionTest.java   View source code 5 votes vote down vote up
/**
 * Tests fix for BUG#11798 - Pstmt.setObject(...., Types.BOOLEAN) throws
 * exception.
 * 
 * @throws Exception
 *             if the test fails.
 */
public void testBug11798() throws Exception {
    try {
        this.pstmt = this.conn.prepareStatement("SELECT ?");
        this.pstmt.setObject(1, Boolean.TRUE, Types.BOOLEAN);
        this.pstmt.setObject(1, new BigDecimal("1"), Types.BOOLEAN);
        this.pstmt.setObject(1, "true", Types.BOOLEAN);
    } finally {
        if (this.pstmt != null) {
            this.pstmt.close();
            this.pstmt = null;
        }
    }
}
 
Example 32
Project: BibliotecaPS   File: ResultSetImpl.java   View source code 5 votes vote down vote up
private void throwRangeException(String valueAsString, int columnIndex, int jdbcType) throws SQLException {
    String datatype = null;

    switch (jdbcType) {
        case Types.TINYINT:
            datatype = "TINYINT";
            break;
        case Types.SMALLINT:
            datatype = "SMALLINT";
            break;
        case Types.INTEGER:
            datatype = "INTEGER";
            break;
        case Types.BIGINT:
            datatype = "BIGINT";
            break;
        case Types.REAL:
            datatype = "REAL";
            break;
        case Types.FLOAT:
            datatype = "FLOAT";
            break;
        case Types.DOUBLE:
            datatype = "DOUBLE";
            break;
        case Types.DECIMAL:
            datatype = "DECIMAL";
            break;
        default:
            datatype = " (JDBC type '" + jdbcType + "')";
    }

    throw SQLError.createSQLException("'" + valueAsString + "' in column '" + columnIndex + "' is outside valid range for the datatype " + datatype + ".",
            SQLError.SQL_STATE_NUMERIC_VALUE_OUT_OF_RANGE, getExceptionInterceptor());
}
 
Example 33
Project: spark-project   File: RecordBuilder.java   View source code 5 votes vote down vote up
@SuppressWarnings("unchecked")
public static final void buildWithCallback(AbstractConfig config, ResultSet rs, final Callback callback) throws SQLException {
	ResultSetMetaData rsmd = rs.getMetaData();
	int columnCount = rsmd.getColumnCount();
	String[] labelNames = new String[columnCount + 1];
	int[] types = new int[columnCount + 1];
	buildLabelNamesAndTypes(rsmd, labelNames, types);
	while (rs.next()) {
		Record record = new Record();
		record.setColumnsMap(config.containerFactory.getColumnsMap());
		Map<String, Object> columns = record.getColumns();
		for (int i=1; i<=columnCount; i++) {
			Object value;
			if (types[i] < Types.BLOB)
				value = rs.getObject(i);
			else if (types[i] == Types.CLOB)
				value = ModelBuilder.handleClob(rs.getClob(i));
			else if (types[i] == Types.NCLOB)
				value = ModelBuilder.handleClob(rs.getNClob(i));
			else if (types[i] == Types.BLOB)
				value = ModelBuilder.handleBlob(rs.getBlob(i));
			else
				value = rs.getObject(i);
			
			columns.put(labelNames[i], value);
		}
		int rowIndex = rs.getRow();
		if (callback != null) {
			callback.invoke(record, rowIndex);
		}
	}
}
 
Example 34
Project: OpenVertretung   File: DatabaseMetaData.java   View source code 5 votes vote down vote up
protected Field[] createColumnsFields() {
    Field[] fields = new Field[24];
    fields[0] = new Field("", "TABLE_CAT", Types.CHAR, 255);
    fields[1] = new Field("", "TABLE_SCHEM", Types.CHAR, 0);
    fields[2] = new Field("", "TABLE_NAME", Types.CHAR, 255);
    fields[3] = new Field("", "COLUMN_NAME", Types.CHAR, 32);
    fields[4] = new Field("", "DATA_TYPE", Types.INTEGER, 5);
    fields[5] = new Field("", "TYPE_NAME", Types.CHAR, 16);
    fields[6] = new Field("", "COLUMN_SIZE", Types.INTEGER, Integer.toString(Integer.MAX_VALUE).length());
    fields[7] = new Field("", "BUFFER_LENGTH", Types.INTEGER, 10);
    fields[8] = new Field("", "DECIMAL_DIGITS", Types.INTEGER, 10);
    fields[9] = new Field("", "NUM_PREC_RADIX", Types.INTEGER, 10);
    fields[10] = new Field("", "NULLABLE", Types.INTEGER, 10);
    fields[11] = new Field("", "REMARKS", Types.CHAR, 0);
    fields[12] = new Field("", "COLUMN_DEF", Types.CHAR, 0);
    fields[13] = new Field("", "SQL_DATA_TYPE", Types.INTEGER, 10);
    fields[14] = new Field("", "SQL_DATETIME_SUB", Types.INTEGER, 10);
    fields[15] = new Field("", "CHAR_OCTET_LENGTH", Types.INTEGER, Integer.toString(Integer.MAX_VALUE).length());
    fields[16] = new Field("", "ORDINAL_POSITION", Types.INTEGER, 10);
    fields[17] = new Field("", "IS_NULLABLE", Types.CHAR, 3);
    fields[18] = new Field("", "SCOPE_CATALOG", Types.CHAR, 255);
    fields[19] = new Field("", "SCOPE_SCHEMA", Types.CHAR, 255);
    fields[20] = new Field("", "SCOPE_TABLE", Types.CHAR, 255);
    fields[21] = new Field("", "SOURCE_DATA_TYPE", Types.SMALLINT, 10);
    fields[22] = new Field("", "IS_AUTOINCREMENT", Types.CHAR, 3); // JDBC 4
    fields[23] = new Field("", "IS_GENERATEDCOLUMN", Types.CHAR, 3); // JDBC 4.1
    return fields;
}
 
Example 35
Project: org.mybatis.generator.core-1.3.5   File: JdbcTypeNameTranslator.java   View source code 5 votes vote down vote up
/**
 * Translates from the string representation of the type to the
 * java.sql.Types value.
 * 
 * @param jdbcTypeName
 *            the iBATIS String representation of a JDBC type
 * @return a value from java.sql.Types
 */
public static int getJdbcType(String jdbcTypeName) {
    Integer answer = nameToType.get(jdbcTypeName);
    if (answer == null) {
        answer = Types.OTHER;
    }

    return answer;
}
 
Example 36
Project: NICON   File: UtilitarioDao.java   View source code 5 votes vote down vote up
public Object regBankAndTaxa(Object o, int i) {
    Object re = "";
    if (i == 1) {
        ComoBox box = (ComoBox) o;
        re = Call.callSampleFunction("FUNC_REG_BANK", Types.VARCHAR, SessionUtil.getUserlogado().getId(), box.getValue(), box.getCodigoNicon());
    } else if (i == 2) {
        Taxa tax = (Taxa) o; //( moneyName VARCHAR2 , idUser NUMBER , valorCompra FLOAT , valorVenda FLOAT ) 
        re = Call.callSampleFunction("PACK_UTIL.FUNC_SET_TAXA", Types.VARCHAR,
                tax.getMoeda1(), tax.getMoeda2(), SessionUtil.getUserlogado().getId(), tax.getCompraValue(), tax.getVendaValue());
    }
    return re;
}
 
Example 37
Project: hadoop   File: DateSplitter.java   View source code 5 votes vote down vote up
/**  Parse the long-valued timestamp into the appropriate SQL date type. */
private Date longToDate(long val, int sqlDataType) {
  switch (sqlDataType) {
  case Types.DATE:
    return new java.sql.Date(val);
  case Types.TIME:
    return new java.sql.Time(val);
  case Types.TIMESTAMP:
    return new java.sql.Timestamp(val);
  default: // Shouldn't ever hit this case.
    return null;
  }
}
 
Example 38
Project: lams   File: IntoClause.java   View source code 5 votes vote down vote up
private boolean areSqlTypesCompatible(int target, int source) {
	switch ( target ) {
		case Types.TIMESTAMP:
			return source == Types.DATE || source == Types.TIME || source == Types.TIMESTAMP;
		case Types.DATE:
			return source == Types.DATE || source == Types.TIMESTAMP;
		case Types.TIME:
			return source == Types.TIME || source == Types.TIMESTAMP;
		default:
			return target == source;
	}
}
 
Example 39
Project: mintleaf   File: ColumnTest.java   View source code 5 votes vote down vote up
@Test
public void testJavaDataTypeDouble() {
    Column d = new Column();
    d.setDatatype(Types.DOUBLE);
    assertEquals(d.getJavaDataType(), Integer.class);
    d.setDecimalDigits(2);
    assertEquals(d.getJavaDataType(), Double.class);
}
 
Example 40
Project: parabuild-ci   File: TestSql.java   View source code 5 votes vote down vote up
public void testAny() {

        try {
            String ddl =
                "drop table PRICE_RELATE_USER_ORDER_V2 if exists;"
                + "create table PRICE_RELATE_USER_ORDER_V2 "
                + "(ID_ORDER_V2 BIGINT, ID_USER NUMERIC, DATE_CREATE TIMESTAMP)";
            String sql = "insert into PRICE_RELATE_USER_ORDER_V2 "
                         + "(ID_ORDER_V2, ID_USER, DATE_CREATE) " + "values "
                         + "(?, ?, ?)";
            Statement st = connection.createStatement();

            st.execute(ddl);

            PreparedStatement ps = connection.prepareStatement(sql);

            ps.setLong(1, 1);
            ps.setNull(2, Types.NUMERIC);
            ps.setTimestamp(
                3, new java.sql.Timestamp(System.currentTimeMillis()));
            ps.execute();
        } catch (SQLException e) {
            e.printStackTrace();
            System.out.println("TestSql.testAny() error: " + e.getMessage());
        }

        System.out.println("testAny complete");
    }