Example usage for java.sql Types DOUBLE

List of usage examples for java.sql Types DOUBLE

Introduction

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

Prototype

int DOUBLE

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

Click Source Link

Document

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

Usage

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

/**
 * Convert the current row in a ResultSet into a TableRow object.
 *
 * @param results//  w  w  w . j a  va2 s .  c o m
 *            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.apache.hadoop.hive.jdbc.TestJdbcDriver.java

public void testResultSetMetaData() throws SQLException {
    Statement stmt = con.createStatement();

    ResultSet res = stmt.executeQuery("select c1, c2, c3, c4, c5 as a, c6, c7, c8, c9, c10, c11, c12, "
            + "c1*2, sentences(null, null, null) as b, c17, c18, c20 from " + dataTypeTableName + " limit 1");
    ResultSetMetaData meta = res.getMetaData();

    ResultSet colRS = con.getMetaData().getColumns(null, null, dataTypeTableName.toLowerCase(), null);

    assertEquals(17, meta.getColumnCount());

    assertTrue(colRS.next());/*from  ww w . jav a 2 s .co m*/

    assertEquals("c1", meta.getColumnName(1));
    assertEquals(Types.INTEGER, meta.getColumnType(1));
    assertEquals("int", meta.getColumnTypeName(1));
    assertEquals(11, meta.getColumnDisplaySize(1));
    assertEquals(10, meta.getPrecision(1));
    assertEquals(0, meta.getScale(1));

    assertEquals("c1", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.INTEGER, colRS.getInt("DATA_TYPE"));
    assertEquals("int", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(1), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(1), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c2", meta.getColumnName(2));
    assertEquals("boolean", meta.getColumnTypeName(2));
    assertEquals(Types.BOOLEAN, meta.getColumnType(2));
    assertEquals(1, meta.getColumnDisplaySize(2));
    assertEquals(1, meta.getPrecision(2));
    assertEquals(0, meta.getScale(2));

    assertEquals("c2", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.BOOLEAN, colRS.getInt("DATA_TYPE"));
    assertEquals("boolean", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(2), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(2), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c3", meta.getColumnName(3));
    assertEquals(Types.DOUBLE, meta.getColumnType(3));
    assertEquals("double", meta.getColumnTypeName(3));
    assertEquals(25, meta.getColumnDisplaySize(3));
    assertEquals(15, meta.getPrecision(3));
    assertEquals(15, meta.getScale(3));

    assertEquals("c3", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.DOUBLE, colRS.getInt("DATA_TYPE"));
    assertEquals("double", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(3), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(3), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c4", meta.getColumnName(4));
    assertEquals(Types.VARCHAR, meta.getColumnType(4));
    assertEquals("string", meta.getColumnTypeName(4));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(4));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(4));
    assertEquals(0, meta.getScale(4));

    assertEquals("c4", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("string", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(4), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(4), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("a", meta.getColumnName(5));
    assertEquals(Types.VARCHAR, meta.getColumnType(5));
    assertEquals("string", meta.getColumnTypeName(5));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(5));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(5));
    assertEquals(0, meta.getScale(5));

    assertEquals("c5", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("array<int>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(5), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(5), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c6", meta.getColumnName(6));
    assertEquals(Types.VARCHAR, meta.getColumnType(6));
    assertEquals("string", meta.getColumnTypeName(6));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(6));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(6));
    assertEquals(0, meta.getScale(6));

    assertEquals("c6", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("map<int,string>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(6), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(6), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c7", meta.getColumnName(7));
    assertEquals(Types.VARCHAR, meta.getColumnType(7));
    assertEquals("string", meta.getColumnTypeName(7));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(7));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(7));
    assertEquals(0, meta.getScale(7));

    assertEquals("c7", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("map<string,string>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(7), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(7), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c8", meta.getColumnName(8));
    assertEquals(Types.VARCHAR, meta.getColumnType(8));
    assertEquals("string", meta.getColumnTypeName(8));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(8));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(8));
    assertEquals(0, meta.getScale(8));

    assertEquals("c8", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.VARCHAR, colRS.getInt("DATA_TYPE"));
    assertEquals("struct<r:string,s:int,t:double>", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(8), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(8), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c9", meta.getColumnName(9));
    assertEquals(Types.TINYINT, meta.getColumnType(9));
    assertEquals("tinyint", meta.getColumnTypeName(9));
    assertEquals(4, meta.getColumnDisplaySize(9));
    assertEquals(3, meta.getPrecision(9));
    assertEquals(0, meta.getScale(9));

    assertEquals("c9", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.TINYINT, colRS.getInt("DATA_TYPE"));
    assertEquals("tinyint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(9), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(9), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c10", meta.getColumnName(10));
    assertEquals(Types.SMALLINT, meta.getColumnType(10));
    assertEquals("smallint", meta.getColumnTypeName(10));
    assertEquals(6, meta.getColumnDisplaySize(10));
    assertEquals(5, meta.getPrecision(10));
    assertEquals(0, meta.getScale(10));

    assertEquals("c10", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.SMALLINT, colRS.getInt("DATA_TYPE"));
    assertEquals("smallint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(10), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(10), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c11", meta.getColumnName(11));
    assertEquals(Types.FLOAT, meta.getColumnType(11));
    assertEquals("float", meta.getColumnTypeName(11));
    assertEquals(24, meta.getColumnDisplaySize(11));
    assertEquals(7, meta.getPrecision(11));
    assertEquals(7, meta.getScale(11));

    assertEquals("c11", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.FLOAT, colRS.getInt("DATA_TYPE"));
    assertEquals("float", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(11), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(11), colRS.getInt("DECIMAL_DIGITS"));

    assertTrue(colRS.next());

    assertEquals("c12", meta.getColumnName(12));
    assertEquals(Types.BIGINT, meta.getColumnType(12));
    assertEquals("bigint", meta.getColumnTypeName(12));
    assertEquals(20, meta.getColumnDisplaySize(12));
    assertEquals(19, meta.getPrecision(12));
    assertEquals(0, meta.getScale(12));

    assertEquals("c12", colRS.getString("COLUMN_NAME"));
    assertEquals(Types.BIGINT, colRS.getInt("DATA_TYPE"));
    assertEquals("bigint", colRS.getString("TYPE_NAME").toLowerCase());
    assertEquals(meta.getPrecision(12), colRS.getInt("COLUMN_SIZE"));
    assertEquals(meta.getScale(12), colRS.getInt("DECIMAL_DIGITS"));

    assertEquals("_c12", meta.getColumnName(13));
    assertEquals(Types.INTEGER, meta.getColumnType(13));
    assertEquals("int", meta.getColumnTypeName(13));
    assertEquals(11, meta.getColumnDisplaySize(13));
    assertEquals(10, meta.getPrecision(13));
    assertEquals(0, meta.getScale(13));

    assertEquals("b", meta.getColumnName(14));
    assertEquals(Types.VARCHAR, meta.getColumnType(14));
    assertEquals("string", meta.getColumnTypeName(14));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(14));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(14));
    assertEquals(0, meta.getScale(14));

    assertEquals("c17", meta.getColumnName(15));
    assertEquals(Types.TIMESTAMP, meta.getColumnType(15));
    assertEquals("timestamp", meta.getColumnTypeName(15));
    assertEquals(29, meta.getColumnDisplaySize(15));
    assertEquals(29, meta.getPrecision(15));
    assertEquals(9, meta.getScale(15));

    assertEquals("c18", meta.getColumnName(16));
    assertEquals(Types.DECIMAL, meta.getColumnType(16));
    assertEquals("decimal", meta.getColumnTypeName(16));
    assertEquals(Integer.MAX_VALUE, meta.getColumnDisplaySize(16));
    assertEquals(Integer.MAX_VALUE, meta.getPrecision(16));
    assertEquals(Integer.MAX_VALUE, meta.getScale(16));

    assertEquals("c20", meta.getColumnName(17));
    assertEquals(Types.DATE, meta.getColumnType(17));
    assertEquals("date", meta.getColumnTypeName(17));
    assertEquals(10, meta.getColumnDisplaySize(17));
    assertEquals(10, meta.getPrecision(17));
    assertEquals(0, meta.getScale(17));

    for (int i = 1; i <= meta.getColumnCount(); i++) {
        assertFalse(meta.isAutoIncrement(i));
        assertFalse(meta.isCurrency(i));
        assertEquals(ResultSetMetaData.columnNullable, meta.isNullable(i));
    }
}

From source file:com.krawler.portal.tools.ServiceBuilder.java

public void _buildModule(DataObjectOperations dobj, String tablename, String moduleid) {
    Map mapObj = (Map) dobj.getDataObjectMapById("mbFormConfig", "moduleid", moduleid);
    String tableName = null;//from   ww  w.  j  a v a  2s . co  m
    List<ModuleProperty> fieldData = new ArrayList<ModuleProperty>();
    JSONArray jarray = null;
    if (mapObj != null) {
        try {
            JSONObject jobj = new JSONObject(mapObj.get("fielddata").toString());
            tableName = jobj.getString("tablename");
            jarray = jobj.getJSONArray("data");
        } catch (JSONException ex) {
            logger.warn(ex.getMessage(), ex);
            throw new RuntimeException("Module Configuration not found");
        }
    }
    if (jarray.length() == 0) {
        throw new RuntimeException("Module Configuration is incorrect");
    }

    try {
        for (int i = 0; i < jarray.length(); i++) {
            JSONObject jobjtemp = new JSONObject(jarray.get(i).toString());
            String type = jobjtemp.getString("type");
            int fieldType = 1;
            if (type.equalsIgnoreCase("String")) {
                fieldType = Types.VARCHAR;
            } else if (type.equalsIgnoreCase("double")) {
                fieldType = Types.DOUBLE;
            } else if (type.equals("boolean")) {
                fieldType = Types.BIT;
            } else if (type.equalsIgnoreCase("date")) {
                fieldType = Types.DATE;
            } else if (type.equals("int")) {
                fieldType = Types.INTEGER;
            }
            ModuleProperty moduleField = new ModuleProperty(jobjtemp.get("name").toString(), fieldType);
            moduleField.setForeignKey(jobjtemp.optBoolean("foreignid", false));
            moduleField.setPrimaryKey(jobjtemp.optBoolean("primaryid", false));
            moduleField.setDefaultValue(jobjtemp.optString("defaults", ""));
            moduleField.setRefTable(jobjtemp.optString("table", ""));
            moduleField.setRefField(jobjtemp.optString("reffield", ""));
            fieldData.add(moduleField);
        }
    } catch (JSONException ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Module Configuration is incorrect");
    } catch (Exception ex) {
        logger.warn(ex.getMessage(), ex);
        throw new RuntimeException("Module Configuration is incorrect");
    }

    dobj.createModuleTable(tableName, fieldData);
}

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 ww  w  .  j av  a2  s  .c om*/
        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.apache.ddlutils.platform.SqlBuilder.java

/**
 * Generates the string representation of the given value.
 * /*  w w  w  .  j  ava2 s  .  c  o m*/
 * @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.easyrec.store.dao.core.impl.ItemAssocDAOMysqlImpl.java

@Override
public int removeItemAssocsQBE(ItemAssocVO<Integer, Integer> itemAssoc) {
    // validate input parameters
    validateOneAttributeSet(itemAssoc);//from  w w  w.j a  v  a2  s  .c  o m

    if (logger.isDebugEnabled()) {
        logger.debug("removing 'itemAssoc' that match the following Example '" + itemAssoc + "'");
    }

    StringBuilder sqlString = new StringBuilder("DELETE FROM ");
    sqlString.append(DEFAULT_TABLE_NAME);
    sqlString.append(" WHERE ");

    List<Object> args = Lists.newArrayList();
    List<Integer> argt = Lists.newArrayList();

    // add constraints to the query
    if (itemAssoc.getId() != null) {
        sqlString.append(DEFAULT_ID_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getId());
        argt.add(Types.INTEGER);
    }
    if (itemAssoc.getTenant() != null) {
        sqlString.append(DEFAULT_TENANT_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getTenant());
        argt.add(Types.INTEGER);
    }
    if (itemAssoc.getItemFrom() != null) {
        ItemVO<Integer, Integer> itemFrom = itemAssoc.getItemFrom();
        if (itemFrom.getItem() != null) {
            sqlString.append(DEFAULT_ITEM_FROM_COLUMN_NAME);
            sqlString.append("=? AND ");

            args.add(itemFrom.getItem());
            argt.add(Types.INTEGER);
        }
        if (itemFrom.getType() != null) {
            sqlString.append(DEFAULT_ITEM_FROM_TYPE_COLUMN_NAME);
            sqlString.append("=? AND ");

            args.add(itemFrom.getType());
            argt.add(Types.INTEGER);
        }
    }
    if (itemAssoc.getAssocType() != null) {
        sqlString.append(DEFAULT_ASSOC_TYPE_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getAssocType());
        argt.add(Types.INTEGER);
    }
    if (itemAssoc.getAssocValue() != null) {
        sqlString.append(DEFAULT_ASSOC_VALUE_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getAssocValue());
        argt.add(Types.DOUBLE);
    }
    if (itemAssoc.getItemTo() != null) {
        ItemVO<Integer, Integer> itemTo = itemAssoc.getItemTo();
        if (itemTo.getItem() != null) {
            sqlString.append(DEFAULT_ITEM_TO_COLUMN_NAME);
            sqlString.append("=? AND ");

            args.add(itemTo.getItem());
            argt.add(Types.INTEGER);
        }
        if (itemTo.getType() != null) {
            sqlString.append(DEFAULT_ITEM_TO_TYPE_COLUMN_NAME);
            sqlString.append("=? AND ");

            args.add(itemTo.getType());
            argt.add(Types.INTEGER);
        }
    }
    if (itemAssoc.getSourceType() != null) {
        sqlString.append(DEFAULT_SOURCE_TYPE_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getSourceType());
        argt.add(Types.INTEGER);
    }
    if (itemAssoc.getSourceInfo() != null) {
        sqlString.append(DEFAULT_SOURCE_INFO_COLUMN_NAME);
        sqlString.append(" LIKE ? AND ");

        args.add(itemAssoc.getSourceInfo());
        argt.add(Types.VARCHAR);
    }
    if (itemAssoc.getViewType() != null) {
        sqlString.append(DEFAULT_VIEW_TYPE_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.getViewType());
        argt.add(Types.INTEGER);
    }
    if (itemAssoc.isActive() != null) {
        sqlString.append(DEFAULT_ACTIVE_COLUMN_NAME);
        sqlString.append("=? AND ");

        args.add(itemAssoc.isActive());
        argt.add(Types.BOOLEAN);
    }
    if (itemAssoc.getChangeDate() != null) {
        sqlString.append("changeDate");
        sqlString.append("=? AND ");

        args.add(itemAssoc.getChangeDate());
        argt.add(Types.TIMESTAMP);
    }

    // remove trailing " AND "
    sqlString.delete(sqlString.length() - 5, sqlString.length());

    return getJdbcTemplate().update(sqlString.toString(), args.toArray(), Ints.toArray(argt));
}

From source file:org.apache.sqoop.mapreduce.hcat.SqoopHCatUtilities.java

/**
* Resolve a database-specific type to HCat data type. Largely follows Sqoop's
* hive translation.//from   w  w  w .  j  a v a2  s.co  m
* @param sqlType
*          sql type
* @return hcat type
*/
public static String toHCatType(int sqlType) {
    switch (sqlType) {

    // Ideally TINYINT and SMALLINT should be mapped to their
    // HCat equivalents tinyint and smallint respectively
    // But the Sqoop Java type conversion has them mapped to Integer
    // Even though the referenced Java doc clearly recommends otherwise.
    // Changing this now can cause many of the sequence file usages to
    // break as value class implementations will change. So, we
    // just use the same behavior here.
    case Types.SMALLINT:
    case Types.TINYINT:
    case Types.INTEGER:
        return "int";

    case Types.VARCHAR:
        return "varchar";
    case Types.CHAR:
        return "char";
    case Types.LONGVARCHAR:
    case Types.NVARCHAR:
    case Types.NCHAR:
    case Types.LONGNVARCHAR:
    case Types.DATE:
    case Types.TIME:
    case Types.TIMESTAMP:
    case Types.CLOB:
        return "string";

    case Types.FLOAT:
    case Types.REAL:
        return "float";

    case Types.NUMERIC:
    case Types.DECIMAL:
        return "decimal";

    case Types.DOUBLE:
        return "double";

    case Types.BIT:
    case Types.BOOLEAN:
        return "boolean";

    case Types.BIGINT:
        return "bigint";

    case Types.BINARY:
    case Types.VARBINARY:
    case Types.BLOB:
    case Types.LONGVARBINARY:
        return "binary";

    default:
        throw new IllegalArgumentException("Cannot convert SQL type to HCatalog type " + sqlType);
    }
}

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

/**
 * This method reads table column meta data.
 *
 * @param tableName Name of the table/*w ww  . j a  v  a  2s  . c o m*/
 * @return table MetaData
 * @throws ODataServiceFault
 */
private Map<String, DataColumn> readTableColumnMetaData(String tableName, DatabaseMetaData meta)
        throws ODataServiceFault {
    ResultSet resultSet = null;
    Map<String, DataColumn> columnMap = new HashMap<>();
    try {
        resultSet = meta.getColumns(null, null, tableName, null);
        int i = 1;
        while (resultSet.next()) {
            String columnName = resultSet.getString("COLUMN_NAME");
            int columnType = resultSet.getInt("DATA_TYPE");
            int size = resultSet.getInt("COLUMN_SIZE");
            boolean nullable = resultSet.getBoolean("NULLABLE");
            String columnDefaultVal = resultSet.getString("COLUMN_DEF");
            int precision = resultSet.getMetaData().getPrecision(i);
            int scale = resultSet.getMetaData().getScale(i);
            DataColumn column = new DataColumn(columnName, getODataDataType(columnType), i, nullable, size);
            if (null != columnDefaultVal) {
                column.setDefaultValue(columnDefaultVal);
            }
            if (Types.DOUBLE == columnType || Types.FLOAT == columnType || Types.DECIMAL == columnType
                    || Types.NUMERIC == columnType || Types.REAL == columnType) {
                column.setPrecision(precision);
                if (scale == 0) {
                    //setting default scale as 5
                    column.setScale(precision);
                } else {
                    column.setScale(scale);
                }
            }
            columnMap.put(columnName, column);
            addDataType(tableName, columnName, columnType);
            i++;
        }
        return columnMap;
    } catch (SQLException e) {
        throw new ODataServiceFault(e,
                "Error in reading table meta data in " + tableName + " table. :" + e.getMessage());
    } finally {
        releaseResources(resultSet, null);
    }
}

From source file:org.jumpmind.symmetric.db.AbstractTriggerTemplate.java

protected String buildKeyVariablesDeclare(Column[] columns, String prefix) {
    String text = "";
    for (int i = 0; i < columns.length; i++) {
        text += "declare @" + prefix + "pk" + i + " ";
        switch (columns[i].getMappedTypeCode()) {
        case Types.TINYINT:
        case Types.SMALLINT:
        case Types.INTEGER:
        case Types.BIGINT:
            text += "bigint\n";
            break;
        case Types.NUMERIC:
        case Types.DECIMAL:
            text += "decimal\n";
            break;
        case Types.FLOAT:
        case Types.REAL:
        case Types.DOUBLE:
            text += "float\n";
            break;
        case Types.CHAR:
        case Types.VARCHAR:
        case ColumnTypes.NVARCHAR:
        case ColumnTypes.LONGNVARCHAR:
        case Types.LONGVARCHAR:
            text += "varchar(1000)\n";
            break;
        case Types.DATE:
            text += "date\n";
            break;
        case Types.TIME:
            text += "time\n";
            break;
        case Types.TIMESTAMP:
            text += "datetime\n";
            break;
        case Types.BOOLEAN:
        case Types.BIT:
            text += "bit\n";
            break;
        case Types.CLOB:
            text += "varchar(max)\n";
            break;
        case Types.BLOB:
        case Types.BINARY:
        case Types.VARBINARY:
        case Types.LONGVARBINARY:
        case -10: // SQL-Server ntext binary type
            text += "varbinary(max)\n";
            break;
        case Types.OTHER:
            text += "varbinary(max)\n";
            break;
        default://from  w w  w. j  av a2s.  c  om
            if (columns[i].getJdbcTypeName() != null
                    && columns[i].getJdbcTypeName().equalsIgnoreCase("interval")) {
                text += "interval";
                break;
            }
            throw new NotImplementedException(columns[i] + " is of type " + columns[i].getMappedType());
        }
    }

    return text;
}

From source file:com.mirth.connect.donkey.test.util.TestUtils.java

private static String typeToString(int sqlType) {
    switch (sqlType) {
    case Types.ARRAY:
        return "ARRAY";
    case Types.BIGINT:
        return "BIGINT";
    case Types.BINARY:
        return "BINARY";
    case Types.BIT:
        return "BIT";
    case Types.BLOB:
        return "BLOB";
    case Types.BOOLEAN:
        return "BOOLEAN";
    case Types.CHAR:
        return "CHAR";
    case Types.CLOB:
        return "CLOB";
    case Types.DATALINK:
        return "DATALINK";
    case Types.DATE:
        return "DATE";
    case Types.DECIMAL:
        return "DECIMAL";
    case Types.DISTINCT:
        return "DISTINCT";
    case Types.DOUBLE:
        return "DOUBLE";
    case Types.FLOAT:
        return "FLOAT";
    case Types.INTEGER:
        return "INTEGER";
    case Types.JAVA_OBJECT:
        return "JAVA_OBJECT";
    case Types.LONGNVARCHAR:
        return "LONGNVARCHAR";
    case Types.LONGVARBINARY:
        return "LONGVARBINARY";
    case Types.LONGVARCHAR:
        return "LONGVARCHAR";
    case Types.NCHAR:
        return "NCHAR";
    case Types.NCLOB:
        return "NCLOB";
    case Types.NULL:
        return "NULL";
    case Types.NUMERIC:
        return "NUMERIC";
    case Types.NVARCHAR:
        return "NVARCHAR";
    case Types.OTHER:
        return "OTHER";
    case Types.REAL:
        return "REAL";
    case Types.REF:
        return "REF";
    case Types.ROWID:
        return "ROWID";
    case Types.SMALLINT:
        return "SMALLINT";
    case Types.SQLXML:
        return "SQLXML";
    case Types.STRUCT:
        return "STRUCT";
    case Types.TIME:
        return "TIME";
    case Types.TIMESTAMP:
        return "TIMESTAMP";
    case Types.TINYINT:
        return "TINYINT";
    case Types.VARBINARY:
        return "VARBINARY";
    case Types.VARCHAR:
        return "VARCHAR";
    default://  ww  w .ja v  a2  s  .  c om
        return "UNKNOWN";
    }
}