Example usage for java.sql Types NUMERIC

List of usage examples for java.sql Types NUMERIC

Introduction

In this page you can find the example usage for java.sql Types NUMERIC.

Prototype

int NUMERIC

To view the source code for java.sql Types NUMERIC.

Click Source Link

Document

The constant in the Java programming language, sometimes referred to as a type code, that identifies the generic SQL type NUMERIC.

Usage

From source file:org.jumpmind.vaadin.ui.sqlexplorer.TabularResultLayout.java

private void setEditor(Grid.Column gridColumn, Column tableColumn, List<TextField> primaryKeyEditors) {
    TextField editor = new TextField();
    int typeCode = tableColumn.getMappedTypeCode();

    switch (typeCode) {
    case Types.DATE:
        editor.setConverter(new ObjectConverter(Date.class, typeCode));
        break;/*  w w w  . ja v  a 2 s  .  c  om*/
    case Types.TIME:
        editor.setConverter(new ObjectConverter(Time.class, typeCode));
        break;
    case Types.TIMESTAMP:
        editor.setConverter(new ObjectConverter(Timestamp.class, typeCode));
        break;
    case Types.BIT:
        editor.setConverter(new StringToBooleanConverter());
        break;
    case Types.TINYINT:
    case Types.SMALLINT:
    case Types.BIGINT:
    case Types.INTEGER:
        editor.setConverter(new StringToLongConverter() {
            private static final long serialVersionUID = 1L;

            public NumberFormat getFormat(Locale locale) {
                NumberFormat format = super.getFormat(locale);
                format.setGroupingUsed(false);
                return format;
            }
        });
        break;
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.REAL:
    case Types.NUMERIC:
    case Types.DECIMAL:
        editor.setConverter(new StringToBigDecimalConverter() {
            private static final long serialVersionUID = 1L;

            public NumberFormat getFormat(Locale locale) {
                NumberFormat format = super.getFormat(locale);
                format.setGroupingUsed(false);
                return format;
            }
        });
        break;
    default:
        break;
    }

    editor.addValidator(new TableChangeValidator(editor, tableColumn));

    editor.setNullRepresentation("");
    if (!tableColumn.isRequired()) {
        editor.setNullSettingAllowed(true);
    }

    if (tableColumn.isPrimaryKey()) {
        primaryKeyEditors.add(editor);
    }

    gridColumn.setEditorField(editor);
}

From source file:org.dspace.storage.rdbms.MockDatabaseManager.java

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results/*from  www. java2 s  .c  om*/
 *            A ResultSet to process
 * @param table
 *            The name of the table
 * @param pColumnNames
 *            The name of the columns in this resultset
 * @return A TableRow object with the data from the ResultSet
 * @exception SQLException
 *                If a database error occurs
 */
@Mock
static TableRow process(ResultSet results, String table, List<String> pColumnNames) throws SQLException {
    String dbName = ConfigurationManager.getProperty("db.name");
    ResultSetMetaData meta = results.getMetaData();
    int columns = meta.getColumnCount() + 1;

    // If we haven't been passed the column names try to generate them from the metadata / table
    List<String> columnNames = pColumnNames != null ? pColumnNames
            : ((table == null) ? getColumnNames(meta) : getColumnNames(table));

    TableRow row = new TableRow(canonicalize(table), columnNames);

    // Process the columns in order
    // (This ensures maximum backwards compatibility with
    // old JDBC drivers)
    for (int i = 1; i < columns; i++) {
        String name = meta.getColumnName(i);
        int jdbctype = meta.getColumnType(i);

        if (jdbctype == Types.BIT || jdbctype == Types.BOOLEAN) {
            row.setColumn(name, results.getBoolean(i));
        } else if ((jdbctype == Types.INTEGER) || (jdbctype == Types.NUMERIC) || (jdbctype == Types.DECIMAL)) {
            // If we are using oracle
            if ("oracle".equals(dbName)) {
                // Test the value from the record set. If it can be represented using an int, do so.
                // Otherwise, store it as long
                long longValue = results.getLong(i);
                if (longValue <= (long) Integer.MAX_VALUE)
                    row.setColumn(name, (int) longValue);
                else
                    row.setColumn(name, longValue);
            } else
                row.setColumn(name, results.getInt(i));
        } else if (jdbctype == Types.BIGINT) {
            row.setColumn(name, results.getLong(i));
        } else if (jdbctype == Types.DOUBLE) {
            row.setColumn(name, results.getDouble(i));
        } else if (jdbctype == Types.CLOB && "oracle".equals(dbName)) {
            // Support CLOBs in place of TEXT columns in Oracle
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.VARCHAR) {
            /*try
            {
            byte[] bytes = results.getBytes(i);
                    
            if (bytes != null)
            {
                String mystring = new String(results.getBytes(i),
                        "UTF-8");
                row.setColumn(name, mystring);
            }
            else
            {
                row.setColumn(name, results.getString(i));
            }
                    
            }
            catch (UnsupportedEncodingException e)
            {
            // do nothing, UTF-8 is built in!
            }*/
            //removing issue with H2 and getBytes
            row.setColumn(name, results.getString(i));
        } else if (jdbctype == Types.DATE) {
            row.setColumn(name, results.getDate(i));
        } else if (jdbctype == Types.TIME) {
            row.setColumn(name, results.getTime(i));
        } else if (jdbctype == Types.TIMESTAMP) {
            row.setColumn(name, results.getTimestamp(i));
        } else {
            throw new IllegalArgumentException("Unsupported JDBC type: " + jdbctype + " (" + name + ")");
        }

        if (results.wasNull()) {
            row.setColumnNull(name);
        }
    }

    // Now that we've prepped the TableRow, reset the flags so that we can detect which columns have changed
    row.resetChanged();
    return row;
}

From source file:org.wso2.carbon.dataservices.core.odata.RDBMSDataHandler.java

private String getValueFromResultSet(int columnType, String column, ResultSet resultSet) throws SQLException {
    String paramValue;//from ww  w.j a  v a 2s  .c o  m
    switch (columnType) {
    case Types.INTEGER:
        /* fall through */
    case Types.TINYINT:
        /* fall through */
    case Types.SMALLINT:
        paramValue = ConverterUtil.convertToString(resultSet.getInt(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.DOUBLE:
        paramValue = ConverterUtil.convertToString(resultSet.getDouble(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.VARCHAR:
        /* fall through */
    case Types.CHAR:
        /* fall through */
    case Types.CLOB:
        /* fall through */
    case Types.LONGVARCHAR:
        paramValue = resultSet.getString(column);
        break;
    case Types.BOOLEAN:
        /* fall through */
    case Types.BIT:
        paramValue = ConverterUtil.convertToString(resultSet.getBoolean(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.BLOB:
        Blob sqlBlob = resultSet.getBlob(column);
        if (sqlBlob != null) {
            paramValue = this.getBase64StringFromInputStream(sqlBlob.getBinaryStream());
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.BINARY:
        /* fall through */
    case Types.LONGVARBINARY:
        /* fall through */
    case Types.VARBINARY:
        InputStream binInStream = resultSet.getBinaryStream(column);
        if (binInStream != null) {
            paramValue = this.getBase64StringFromInputStream(binInStream);
        } else {
            paramValue = null;
        }
        break;
    case Types.DATE:
        Date sqlDate = resultSet.getDate(column);
        if (sqlDate != null) {
            paramValue = ConverterUtil.convertToString(sqlDate);
        } else {
            paramValue = null;
        }
        break;
    case Types.DECIMAL:
        /* fall through */
    case Types.NUMERIC:
        BigDecimal bigDecimal = resultSet.getBigDecimal(column);
        if (bigDecimal != null) {
            paramValue = ConverterUtil.convertToString(bigDecimal);
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.FLOAT:
        paramValue = ConverterUtil.convertToString(resultSet.getFloat(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.TIME:
        Time sqlTime = resultSet.getTime(column);
        if (sqlTime != null) {
            paramValue = this.convertToTimeString(sqlTime);
        } else {
            paramValue = null;
        }
        break;
    case Types.LONGNVARCHAR:
        /* fall through */
    case Types.NCHAR:
        /* fall through */
    case Types.NCLOB:
        /* fall through */
    case Types.NVARCHAR:
        paramValue = resultSet.getNString(column);
        break;
    case Types.BIGINT:
        paramValue = ConverterUtil.convertToString(resultSet.getLong(column));
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    case Types.TIMESTAMP:
        Timestamp sqlTimestamp = resultSet.getTimestamp(column);
        if (sqlTimestamp != null) {
            paramValue = this.convertToTimestampString(sqlTimestamp);
        } else {
            paramValue = null;
        }
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    /* handle all other types as strings */
    default:
        paramValue = resultSet.getString(column);
        paramValue = resultSet.wasNull() ? null : paramValue;
        break;
    }
    return paramValue;
}

From source file:org.springframework.jdbc.object.SqlQueryTests.java

public void testNamedParameterInListQuery() throws SQLException {
    mockResultSet.next();/*  w ww .java  2  s .com*/
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(1);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("rod");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(2);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("juergen");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setObject(2, new Integer(2), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID_IN_LIST_1, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    class CustomerQuery extends MappingSqlQuery {

        public CustomerQuery(DataSource ds) {
            super(ds, SELECT_ID_FORENAME_WHERE_ID_IN_LIST_2);
            setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
            declareParameter(new SqlParameter("ids", Types.NUMERIC));
            compile();
        }

        protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
            Customer cust = new Customer();
            cust.setId(rs.getInt(COLUMN_NAMES[0]));
            cust.setForename(rs.getString(COLUMN_NAMES[1]));
            return cust;
        }

        public List findCustomers(List ids) {
            Map params = new HashMap();
            params.put("ids", ids);
            return (List) executeByNamedParam(params);
        }
    }

    CustomerQuery query = new CustomerQuery(mockDataSource);
    List ids = new ArrayList();
    ids.add(new Integer(1));
    ids.add(new Integer(2));
    List cust = query.findCustomers(ids);

    assertEquals("We got two customers back", cust.size(), 2);
    Assert.assertEquals("First customer id was assigned correctly", ((Customer) cust.get(0)).getId(), 1);
    Assert.assertEquals("First customer forename was assigned correctly",
            ((Customer) cust.get(0)).getForename(), "rod");
    Assert.assertEquals("Second customer id was assigned correctly", ((Customer) cust.get(1)).getId(), 2);
    Assert.assertEquals("Second customer forename was assigned correctly",
            ((Customer) cust.get(1)).getForename(), "juergen");
}

From source file:com.mmnaseri.dragonfly.metadata.impl.AnnotationTableMetadataResolver.java

private static int getColumnType(Class<?> javaType, Method method, ColumnMetadata foreignReference) {
    final int dimensions = ReflectionUtils.getArrayDimensions(javaType);
    javaType = ReflectionUtils.mapType(ReflectionUtils.getComponentType(javaType));
    if (dimensions > 1) {
        throw new UnsupportedColumnTypeError("Arrays of dimension > 1 are not supported");
    }/*from  w  w  w  .  ja va 2 s. c  o  m*/
    if (Byte.class.equals(javaType) && dimensions == 0) {
        return Types.TINYINT;
    } else if (Short.class.equals(javaType)) {
        return Types.SMALLINT;
    } else if (Integer.class.equals(javaType)) {
        return Types.INTEGER;
    } else if (Long.class.equals(javaType)) {
        return Types.BIGINT;
    } else if (Float.class.equals(javaType)) {
        return Types.FLOAT;
    } else if (Double.class.equals(javaType)) {
        return Types.DOUBLE;
    } else if (BigDecimal.class.equals(javaType)) {
        return Types.DECIMAL;
    } else if (BigInteger.class.equals(javaType)) {
        return Types.NUMERIC;
    } else if (Character.class.equals(javaType)) {
        return Types.CHAR;
    } else if (String.class.equals(javaType) || Class.class.equals(javaType)) {
        if (method != null && method.isAnnotationPresent(Column.class)
                && method.getAnnotation(Column.class).length() > 0) {
            return Types.VARCHAR;
        } else {
            return Types.LONGVARCHAR;
        }
    } else if (Date.class.isAssignableFrom(javaType)) {
        if (javaType.equals(java.sql.Date.class)) {
            return Types.DATE;
        } else if (javaType.equals(Time.class)) {
            return Types.TIME;
        } else if (javaType.equals(java.sql.Timestamp.class)) {
            return Types.TIMESTAMP;
        }
        final TemporalType temporalType = method != null && method.isAnnotationPresent(Temporal.class)
                ? method.getAnnotation(Temporal.class).value()
                : null;
        return (temporalType == null || temporalType.equals(TemporalType.TIMESTAMP)) ? Types.TIMESTAMP
                : (temporalType.equals(TemporalType.DATE) ? Types.DATE : Types.TIME);
    } else if (Byte.class.equals(javaType) && dimensions > 0) {
        return Types.VARBINARY;
    } else if (Enum.class.isAssignableFrom(javaType)) {
        return Types.VARCHAR;
    } else if (Boolean.class.equals(javaType)) {
        return Types.BOOLEAN;
    } else if (Collection.class.isAssignableFrom(javaType)
            && method.isAnnotationPresent(BasicCollection.class)) {
        return Types.LONGVARCHAR;
    }
    if (foreignReference != null) {
        return Integer.MIN_VALUE;
    }
    return Types.LONGVARCHAR;
}

From source file:com.etcc.csc.dao.OraclePaymentDAO.java

public long hasVBInvoices(String licPlate, String licState, BigDecimal inv_id, BigDecimal violator_id)
        throws EtccErrorMessageException, Exception {

    long result = 0;
    try {//w  ww. jav  a2 s . co m
        setConnection(Util.getDbConnection());

        cstmt = conn.prepareCall("{? = call olcsc_VB_inv.has_invoices(?,?,?,?)}");

        cstmt.registerOutParameter(1, Types.VARCHAR);
        cstmt.setString(2, licPlate);
        cstmt.setString(3, licState);
        cstmt.setBigDecimal(4, inv_id);
        cstmt.registerOutParameter(4, Types.NUMERIC);
        cstmt.setBigDecimal(5, violator_id);
        cstmt.execute();

        String violationExists = cstmt.getString(1);
        logger.info("the violation exist value is " + violationExists);
        if (violationExists.equals("Y")) {
            result = cstmt.getLong(4);

        }
        logger.info("the result value is " + result);
    } catch (Throwable t) {
        throw new EtccException("Error running hasVBInvoices: " + t, t);
    } finally {
        closeConnection();
    }

    return result;

}

From source file:org.openmrs.module.sync.api.db.hibernate.HibernateSyncDAO.java

public void exportChildDB(String uuidForChild, OutputStream os) throws DAOException {
    PrintStream out = new PrintStream(os);
    Set<String> tablesToSkip = new HashSet<String>();
    {/*from w ww  .j a  v  a  2  s. c  o  m*/
        tablesToSkip.add("hl7_in_archive");
        tablesToSkip.add("hl7_in_queue");
        tablesToSkip.add("hl7_in_error");
        tablesToSkip.add("formentry_archive");
        tablesToSkip.add("formentry_queue");
        tablesToSkip.add("formentry_error");
        tablesToSkip.add("sync_class");
        tablesToSkip.add("sync_import");
        tablesToSkip.add("sync_record");
        tablesToSkip.add("sync_server");
        tablesToSkip.add("sync_server_class");
        tablesToSkip.add("sync_server_record");
        // TODO: figure out which other tables to skip
        // tablesToSkip.add("obs");
        // tablesToSkip.add("concept");
        // tablesToSkip.add("patient");
    }
    List<String> tablesToDump = new ArrayList<String>();
    Session session = sessionFactory.getCurrentSession();
    String schema = (String) session.createSQLQuery("SELECT schema()").uniqueResult();
    log.warn("schema: " + schema);
    // Get all tables that we'll need to dump
    {
        Query query = session.createSQLQuery(
                "SELECT tabs.table_name FROM INFORMATION_SCHEMA.TABLES tabs WHERE tabs.table_schema = '"
                        + schema + "'");
        for (Object tn : query.list()) {
            String tableName = (String) tn;
            if (!tablesToSkip.contains(tableName.toLowerCase()))
                tablesToDump.add(tableName);
        }
    }
    log.warn("tables to dump: " + tablesToDump);

    String thisServerGuid = getGlobalProperty(SyncConstants.PROPERTY_SERVER_UUID);

    // Write the DDL Header as mysqldump does
    {
        out.println("-- ------------------------------------------------------");
        out.println("-- Database dump to create an openmrs child server");
        out.println("-- Schema: " + schema);
        out.println("-- Parent GUID: " + thisServerGuid);
        out.println("-- Parent version: " + OpenmrsConstants.OPENMRS_VERSION);
        out.println("-- ------------------------------------------------------");
        out.println("");
        out.println("/*!40101 SET CHARACTER_SET_CLIENT=utf8 */;");
        out.println("/*!40101 SET NAMES utf8 */;");
        out.println("/*!40103 SET TIME_ZONE='+00:00' */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;");
        out.println("/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;");
        out.println("/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;");
        out.println("/*!40103 SET @OLD_TIME_ZONE=@@TIME_ZONE */;");
        out.println("/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;");
        out.println("/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;");
        out.println("/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;");
        out.println("/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;");
        out.println("");
    }
    try {
        // JDBC way of doing this
        // Connection conn =
        // DriverManager.getConnection("jdbc:mysql://localhost/" + schema,
        // "test", "test");
        Connection conn = sessionFactory.getCurrentSession().connection();
        try {
            Statement st = conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);

            // Get the create database statement
            ResultSet rs = st.executeQuery("SHOW CREATE DATABASE " + schema);
            for (String tableName : tablesToDump) {
                out.println();
                out.println("--");
                out.println("-- Table structure for table `" + tableName + "`");
                out.println("--");
                out.println("DROP TABLE IF EXISTS `" + tableName + "`;");
                out.println("SET @saved_cs_client     = @@character_set_client;");
                out.println("SET character_set_client = utf8;");
                rs = st.executeQuery("SHOW CREATE TABLE " + tableName);
                while (rs.next()) {
                    out.println(rs.getString("Create Table") + ";");
                }
                out.println("SET character_set_client = @saved_cs_client;");
                out.println();

                {
                    out.println("-- Dumping data for table `" + tableName + "`");
                    out.println("LOCK TABLES `" + tableName + "` WRITE;");
                    out.println("/*!40000 ALTER TABLE `" + tableName + "` DISABLE KEYS */;");
                    boolean first = true;

                    rs = st.executeQuery("select * from " + tableName);
                    ResultSetMetaData md = rs.getMetaData();
                    int numColumns = md.getColumnCount();
                    int rowNum = 0;
                    boolean insert = false;

                    while (rs.next()) {
                        if (rowNum == 0) {
                            insert = true;
                            out.print("INSERT INTO `" + tableName + "` VALUES ");
                        }
                        ++rowNum;
                        if (first) {
                            first = false;
                        } else {
                            out.print(", ");
                        }
                        if (rowNum % 20 == 0) {
                            out.println();
                        }
                        out.print("(");
                        for (int i = 1; i <= numColumns; ++i) {
                            if (i != 1) {
                                out.print(",");
                            }
                            if (rs.getObject(i) == null) {
                                out.print("NULL");
                            } else {
                                switch (md.getColumnType(i)) {
                                case Types.VARCHAR:
                                case Types.CHAR:
                                case Types.LONGVARCHAR:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.BIGINT:
                                case Types.DECIMAL:
                                case Types.NUMERIC:
                                    out.print(rs.getBigDecimal(i));
                                    break;
                                case Types.BIT:
                                    out.print(rs.getBoolean(i));
                                    break;
                                case Types.INTEGER:
                                case Types.SMALLINT:
                                case Types.TINYINT:
                                    out.print(rs.getInt(i));
                                    break;
                                case Types.REAL:
                                case Types.FLOAT:
                                case Types.DOUBLE:
                                    out.print(rs.getDouble(i));
                                    break;
                                case Types.BLOB:
                                case Types.VARBINARY:
                                case Types.LONGVARBINARY:
                                    Blob blob = rs.getBlob(i);
                                    out.print("'");
                                    InputStream in = blob.getBinaryStream();
                                    while (true) {
                                        int b = in.read();
                                        if (b < 0) {
                                            break;
                                        }
                                        char c = (char) b;
                                        if (c == '\'') {
                                            out.print("\'");
                                        } else {
                                            out.print(c);
                                        }
                                    }
                                    out.print("'");
                                    break;
                                case Types.CLOB:
                                    out.print("'");
                                    out.print(
                                            rs.getString(i).replaceAll("\n", "\\\\n").replaceAll("'", "\\\\'"));
                                    out.print("'");
                                    break;
                                case Types.DATE:
                                    out.print("'" + rs.getDate(i) + "'");
                                    break;
                                case Types.TIMESTAMP:
                                    out.print("'" + rs.getTimestamp(i) + "'");
                                    break;
                                default:
                                    throw new RuntimeException("TODO: handle type code " + md.getColumnType(i)
                                            + " (name " + md.getColumnTypeName(i) + ")");
                                }
                            }
                        }
                        out.print(")");
                    }
                    if (insert) {
                        out.println(";");
                        insert = false;
                    }

                    out.println("/*!40000 ALTER TABLE `" + tableName + "` ENABLE KEYS */;");
                    out.println("UNLOCK TABLES;");
                    out.println();
                }
            }
        } finally {
            conn.close();
        }

        // Now we mark this as a child
        out.println("-- Now mark this as a child database");
        if (uuidForChild == null)
            uuidForChild = SyncUtil.generateUuid();
        out.println("update global_property set property_value = '" + uuidForChild + "' where property = '"
                + SyncConstants.PROPERTY_SERVER_UUID + "';");

        // Write the footer of the DDL script
        {
            out.println("/*!40103 SET TIME_ZONE=@OLD_TIME_ZONE */;");
            out.println("/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;");
            out.println("/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;");
            out.println("/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;");
            out.println("/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;");
            out.println("/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;");
            out.println("/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;");
            out.println("/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;");
        }
        out.flush();
        out.close();
    } catch (IOException ex) {
        log.error("IOException", ex);

    } catch (SQLException ex) {
        log.error("SQLException", ex);
    }
}

From source file:org.jumpmind.db.sql.JdbcSqlTemplate.java

public void setValues(PreparedStatement ps, Object[] args, int[] argTypes, LobHandler lobHandler)
        throws SQLException {
    for (int i = 1; i <= args.length; i++) {
        Object arg = args[i - 1];
        int argType = argTypes != null && argTypes.length >= i ? argTypes[i - 1] : SqlTypeValue.TYPE_UNKNOWN;
        if (argType == Types.BLOB && lobHandler != null && arg instanceof byte[]) {
            lobHandler.getLobCreator().setBlobAsBytes(ps, i, (byte[]) arg);
        } else if (argType == Types.BLOB && lobHandler != null && arg instanceof String) {
            lobHandler.getLobCreator().setBlobAsBytes(ps, i, arg.toString().getBytes());
        } else if (argType == Types.CLOB && lobHandler != null) {
            lobHandler.getLobCreator().setClobAsString(ps, i, (String) arg);
        } else if ((argType == Types.DECIMAL || argType == Types.NUMERIC) && arg != null) {
            setDecimalValue(ps, i, arg, argType);
        } else if (argType == Types.TINYINT) {
            setTinyIntValue(ps, i, arg, argType);
        } else {/* w w w.jav a  2 s  .c om*/
            StatementCreatorUtils.setParameterValue(ps, i, verifyArgType(arg, argType), arg);
        }
    }
}

From source file:org.apache.ddlutils.platform.SqlBuilder.java

/**
 * Generates the string representation of the given value.
 * //from w  ww  . ja v a2s .  c  om
 * @param column The column
 * @param value  The value
 * @return The string representation
 */
protected String getValueAsString(Column column, Object value) {
    if (value == null) {
        return "NULL";
    }

    StringBuffer result = new StringBuffer();

    // TODO: Handle binary types (BINARY, VARBINARY, LONGVARBINARY, BLOB)
    switch (column.getTypeCode()) {
    case Types.DATE:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueDateFormat() != null)) {
            // TODO: Can the format method handle java.sql.Date properly ?
            result.append(getValueDateFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.TIME:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueTimeFormat() != null)) {
            // TODO: Can the format method handle java.sql.Date properly ?
            result.append(getValueTimeFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.TIMESTAMP:
        result.append(getPlatformInfo().getValueQuoteToken());
        // TODO: SimpleDateFormat does not support nano seconds so we would
        //       need a custom date formatter for timestamps
        result.append(value.toString());
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    case Types.REAL:
    case Types.NUMERIC:
    case Types.FLOAT:
    case Types.DOUBLE:
    case Types.DECIMAL:
        result.append(getPlatformInfo().getValueQuoteToken());
        if (!(value instanceof String) && (getValueNumberFormat() != null)) {
            result.append(getValueNumberFormat().format(value));
        } else {
            result.append(value.toString());
        }
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    default:
        result.append(getPlatformInfo().getValueQuoteToken());
        result.append(escapeStringValue(value.toString()));
        result.append(getPlatformInfo().getValueQuoteToken());
        break;
    }
    return result.toString();
}

From source file:org.springframework.jdbc.object.SqlQueryTests.java

public void testNamedParameterQueryReusingParameter() throws SQLException {
    mockResultSet.next();//  w  ww. j  a  v  a2  s  .com
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(1);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("rod");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(true);
    mockResultSet.getInt("id");
    ctrlResultSet.setReturnValue(2);
    mockResultSet.getString("forename");
    ctrlResultSet.setReturnValue("juergen");
    mockResultSet.next();
    ctrlResultSet.setReturnValue(false);
    mockResultSet.close();
    ctrlResultSet.setVoidCallable();

    mockPreparedStatement.setObject(1, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.setObject(2, new Integer(1), Types.NUMERIC);
    ctrlPreparedStatement.setVoidCallable();
    mockPreparedStatement.executeQuery();
    ctrlPreparedStatement.setReturnValue(mockResultSet);
    if (debugEnabled) {
        mockPreparedStatement.getWarnings();
        ctrlPreparedStatement.setReturnValue(null);
    }
    mockPreparedStatement.close();
    ctrlPreparedStatement.setVoidCallable();

    mockConnection.prepareStatement(SELECT_ID_FORENAME_WHERE_ID_REUSED_1, ResultSet.TYPE_SCROLL_SENSITIVE,
            ResultSet.CONCUR_READ_ONLY);
    ctrlConnection.setReturnValue(mockPreparedStatement);

    replay();

    class CustomerQuery extends MappingSqlQuery {

        public CustomerQuery(DataSource ds) {
            super(ds, SELECT_ID_FORENAME_WHERE_ID_REUSED_2);
            setResultSetType(ResultSet.TYPE_SCROLL_SENSITIVE);
            declareParameter(new SqlParameter("id1", Types.NUMERIC));
            compile();
        }

        protected Object mapRow(ResultSet rs, int rownum) throws SQLException {
            Customer cust = new Customer();
            cust.setId(rs.getInt(COLUMN_NAMES[0]));
            cust.setForename(rs.getString(COLUMN_NAMES[1]));
            return cust;
        }

        public List findCustomers(Integer id) {
            Map params = new HashMap();
            params.put("id1", id);
            return (List) executeByNamedParam(params);
        }
    }

    CustomerQuery query = new CustomerQuery(mockDataSource);
    List cust = query.findCustomers(new Integer(1));

    assertEquals("We got two customers back", cust.size(), 2);
    Assert.assertEquals("First customer id was assigned correctly", ((Customer) cust.get(0)).getId(), 1);
    Assert.assertEquals("First customer forename was assigned correctly",
            ((Customer) cust.get(0)).getForename(), "rod");
    Assert.assertEquals("Second customer id was assigned correctly", ((Customer) cust.get(1)).getId(), 2);
    Assert.assertEquals("Second customer forename was assigned correctly",
            ((Customer) cust.get(1)).getForename(), "juergen");
}