Example usage for java.sql PreparedStatement setByte

List of usage examples for java.sql PreparedStatement setByte

Introduction

In this page you can find the example usage for java.sql PreparedStatement setByte.

Prototype

void setByte(int parameterIndex, byte x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given Java byte value.

Usage

From source file:tinygsn.storage.StorageManager.java

public void executeInsert(CharSequence tableName, DataField[] fields, StreamElement streamElement,
        Connection connection) throws SQLException {
    PreparedStatement ps = null;
    String query = getStatementInsert(tableName, fields).toString();
    try {/*from  w ww  .j  a va2  s .  com*/
        ps = connection.prepareStatement(query);
        int counter = 1;
        for (DataField dataField : fields) {
            if (dataField.getName().equalsIgnoreCase("timed"))
                continue;
            Serializable value = streamElement.getData(dataField.getName());

            switch (dataField.getDataTypeID()) {
            case DataTypes.VARCHAR:
                if (value == null)
                    ps.setNull(counter, Types.VARCHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.CHAR:
                if (value == null)
                    ps.setNull(counter, Types.CHAR);
                else
                    ps.setString(counter, value.toString());
                break;
            case DataTypes.INTEGER:
                if (value == null)
                    ps.setNull(counter, Types.INTEGER);
                else
                    ps.setInt(counter, ((Number) value).intValue());
                break;
            case DataTypes.SMALLINT:
                if (value == null)
                    ps.setNull(counter, Types.SMALLINT);
                else
                    ps.setShort(counter, ((Number) value).shortValue());
                break;
            case DataTypes.TINYINT:
                if (value == null)
                    ps.setNull(counter, Types.TINYINT);
                else
                    ps.setByte(counter, ((Number) value).byteValue());
                break;
            case DataTypes.DOUBLE:
                if (value == null)
                    ps.setNull(counter, Types.DOUBLE);
                else
                    ps.setDouble(counter, ((Number) value).doubleValue());
                break;
            case DataTypes.BIGINT:
                if (value == null)
                    ps.setNull(counter, Types.BIGINT);
                else
                    ps.setLong(counter, ((Number) value).longValue());
                break;
            case DataTypes.BINARY:
                if (value == null)
                    ps.setNull(counter, Types.BINARY);
                else
                    ps.setBytes(counter, (byte[]) value);
                break;
            default:
                // logger.error("The type conversion is not supported for : "
                // + dataField.getName() + "(" + dataField.getDataTypeID() + ") : ");
            }
            counter++;
        }
        ps.setLong(counter, streamElement.getTimeStamp());
        ps.execute();
    } catch (GSNRuntimeException e) {
        // if (e.getType() ==
        // GSNRuntimeException.UNEXPECTED_VIRTUAL_SENSOR_REMOVAL) {
        // if (logger.isDebugEnabled())
        //
        // logger
        // .debug(
        // "An stream element dropped due to unexpected virtual sensor removal. (Stream element: "
        // + streamElement.toString() + ")+ Query: " + query, e);
        // } else
        // logger.warn(
        // "Inserting a stream element failed : " + streamElement.toString(), e);
    } catch (SQLException e) {
        if (e.getMessage().toLowerCase().contains("duplicate entry"))
            // logger
            // .info("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            // else
            // logger
            // .warn("Error occurred on inserting data to the database, an stream element dropped due to: "
            // + e.getMessage()
            // + ". (Stream element: "
            // + streamElement.toString() + ")+ Query: " + query);
            throw e;
    } finally {
        close(ps);
    }
}

From source file:com.alibaba.wasp.jdbc.TestPreparedStatement.java

public void testDataTypes() throws SQLException {
    conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
    conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);
    Statement stat = conn.createStatement();
    PreparedStatement prep;
    ResultSet rs;// www  .java  2  s  . c o  m
    trace("Create tables");
    stat.execute("CREATE TABLE T_INT(ID INT PRIMARY KEY,VALUE INT)");
    stat.execute("CREATE TABLE T_VARCHAR(ID INT PRIMARY KEY,VALUE VARCHAR(255))");
    stat.execute("CREATE TABLE T_DECIMAL_0(ID INT PRIMARY KEY,VALUE DECIMAL(30,0))");
    stat.execute("CREATE TABLE T_DECIMAL_10(ID INT PRIMARY KEY,VALUE DECIMAL(20,10))");
    stat.execute("CREATE TABLE T_DATETIME(ID INT PRIMARY KEY,VALUE DATETIME)");
    prep = conn.prepareStatement("INSERT INTO T_INT VALUES(?,?)", ResultSet.TYPE_FORWARD_ONLY,
            ResultSet.CONCUR_READ_ONLY);
    prep.setInt(1, 1);
    prep.setInt(2, 0);
    prep.executeUpdate();
    prep.setInt(1, 2);
    prep.setInt(2, -1);
    prep.executeUpdate();
    prep.setInt(1, 3);
    prep.setInt(2, 3);
    prep.executeUpdate();
    prep.setInt(1, 4);
    prep.setNull(2, Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 5);
    prep.setBigDecimal(2, new BigDecimal("0"));
    prep.executeUpdate();
    prep.setInt(1, 6);
    prep.setString(2, "-1");
    prep.executeUpdate();
    prep.setInt(1, 7);
    prep.setObject(2, new Integer(3));
    prep.executeUpdate();
    prep.setObject(1, "8");
    // should throw an exception
    prep.setObject(2, null);
    // some databases don't allow calling setObject with null (no data type)
    prep.executeUpdate();
    prep.setInt(1, 9);
    prep.setObject(2, -4, Types.VARCHAR);
    prep.executeUpdate();
    prep.setInt(1, 10);
    prep.setObject(2, "5", Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 11);
    prep.setObject(2, null, Types.INTEGER);
    prep.executeUpdate();
    prep.setInt(1, 12);
    prep.setBoolean(2, true);
    prep.executeUpdate();
    prep.setInt(1, 13);
    prep.setBoolean(2, false);
    prep.executeUpdate();
    prep.setInt(1, 14);
    prep.setByte(2, (byte) -20);
    prep.executeUpdate();
    prep.setInt(1, 15);
    prep.setByte(2, (byte) 100);
    prep.executeUpdate();
    prep.setInt(1, 16);
    prep.setShort(2, (short) 30000);
    prep.executeUpdate();
    prep.setInt(1, 17);
    prep.setShort(2, (short) (-30000));
    prep.executeUpdate();
    prep.setInt(1, 18);
    prep.setLong(2, Integer.MAX_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 19);
    prep.setLong(2, Integer.MIN_VALUE);
    prep.executeUpdate();

    assertTrue(stat.execute("SELECT * FROM T_INT ORDER BY ID"));
    rs = stat.getResultSet();
    assertResultSetOrdered(rs,
            new String[][] { { "1", "0" }, { "2", "-1" }, { "3", "3" }, { "4", null }, { "5", "0" },
                    { "6", "-1" }, { "7", "3" }, { "8", null }, { "9", "-4" }, { "10", "5" }, { "11", null },
                    { "12", "1" }, { "13", "0" }, { "14", "-20" }, { "15", "100" }, { "16", "30000" },
                    { "17", "-30000" }, { "18", "" + Integer.MAX_VALUE }, { "19", "" + Integer.MIN_VALUE }, });

    prep = conn.prepareStatement("INSERT INTO T_DECIMAL_0 VALUES(?,?)");
    prep.setInt(1, 1);
    prep.setLong(2, Long.MAX_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 2);
    prep.setLong(2, Long.MIN_VALUE);
    prep.executeUpdate();
    prep.setInt(1, 3);
    prep.setFloat(2, 10);
    prep.executeUpdate();
    prep.setInt(1, 4);
    prep.setFloat(2, -20);
    prep.executeUpdate();
    prep.setInt(1, 5);
    prep.setFloat(2, 30);
    prep.executeUpdate();
    prep.setInt(1, 6);
    prep.setFloat(2, -40);
    prep.executeUpdate();

    rs = stat.executeQuery("SELECT VALUE FROM T_DECIMAL_0 ORDER BY ID");
    checkBigDecimal(rs, new String[] { "" + Long.MAX_VALUE, "" + Long.MIN_VALUE, "10", "-20", "30", "-40" });
}

From source file:org.apache.phoenix.end2end.DateTimeIT.java

private String initAtable() throws SQLException {
    String tableName = generateUniqueName();
    ensureTableCreated(getUrl(), tableName, ATABLE_NAME, (byte[][]) null, null);
    PreparedStatement stmt = conn.prepareStatement("upsert into " + tableName + "(" + "    ORGANIZATION_ID, "
            + "    ENTITY_ID, " + "    A_STRING, " + "    B_STRING, " + "    A_INTEGER, " + "    A_DATE, "
            + "    X_DECIMAL, " + "    X_LONG, " + "    X_INTEGER," + "    Y_INTEGER," + "    A_BYTE,"
            + "    A_SHORT," + "    A_FLOAT," + "    A_DOUBLE," + "    A_UNSIGNED_FLOAT,"
            + "    A_UNSIGNED_DOUBLE)" + "VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)");
    stmt.setString(1, tenantId);/* w w w. j  a v a2 s  . c o  m*/
    stmt.setString(2, ROW1);
    stmt.setString(3, A_VALUE);
    stmt.setString(4, B_VALUE);
    stmt.setInt(5, 1);
    stmt.setDate(6, date);
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 1);
    stmt.setShort(12, (short) 128);
    stmt.setFloat(13, 0.01f);
    stmt.setDouble(14, 0.0001);
    stmt.setFloat(15, 0.01f);
    stmt.setDouble(16, 0.0001);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW2);
    stmt.setString(3, A_VALUE);
    stmt.setString(4, C_VALUE);
    stmt.setInt(5, 2);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 2);
    stmt.setShort(12, (short) 129);
    stmt.setFloat(13, 0.02f);
    stmt.setDouble(14, 0.0002);
    stmt.setFloat(15, 0.02f);
    stmt.setDouble(16, 0.0002);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW3);
    stmt.setString(3, A_VALUE);
    stmt.setString(4, E_VALUE);
    stmt.setInt(5, 3);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 3);
    stmt.setShort(12, (short) 130);
    stmt.setFloat(13, 0.03f);
    stmt.setDouble(14, 0.0003);
    stmt.setFloat(15, 0.03f);
    stmt.setDouble(16, 0.0003);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW4);
    stmt.setString(3, A_VALUE);
    stmt.setString(4, B_VALUE);
    stmt.setInt(5, 4);
    stmt.setDate(6, date == null ? null : date);
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 4);
    stmt.setShort(12, (short) 131);
    stmt.setFloat(13, 0.04f);
    stmt.setDouble(14, 0.0004);
    stmt.setFloat(15, 0.04f);
    stmt.setDouble(16, 0.0004);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW5);
    stmt.setString(3, B_VALUE);
    stmt.setString(4, C_VALUE);
    stmt.setInt(5, 5);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 5);
    stmt.setShort(12, (short) 132);
    stmt.setFloat(13, 0.05f);
    stmt.setDouble(14, 0.0005);
    stmt.setFloat(15, 0.05f);
    stmt.setDouble(16, 0.0005);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW6);
    stmt.setString(3, B_VALUE);
    stmt.setString(4, E_VALUE);
    stmt.setInt(5, 6);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
    stmt.setBigDecimal(7, null);
    stmt.setNull(8, Types.BIGINT);
    stmt.setNull(9, Types.INTEGER);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 6);
    stmt.setShort(12, (short) 133);
    stmt.setFloat(13, 0.06f);
    stmt.setDouble(14, 0.0006);
    stmt.setFloat(15, 0.06f);
    stmt.setDouble(16, 0.0006);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW7);
    stmt.setString(3, B_VALUE);
    stmt.setString(4, B_VALUE);
    stmt.setInt(5, 7);
    stmt.setDate(6, date == null ? null : date);
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.1));
    stmt.setLong(8, 5L);
    stmt.setInt(9, 5);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 7);
    stmt.setShort(12, (short) 134);
    stmt.setFloat(13, 0.07f);
    stmt.setDouble(14, 0.0007);
    stmt.setFloat(15, 0.07f);
    stmt.setDouble(16, 0.0007);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW8);
    stmt.setString(3, B_VALUE);
    stmt.setString(4, C_VALUE);
    stmt.setInt(5, 8);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 1));
    stmt.setBigDecimal(7, BigDecimal.valueOf(3.9));
    long l = Integer.MIN_VALUE - 1L;
    assert (l < Integer.MIN_VALUE);
    stmt.setLong(8, l);
    stmt.setInt(9, 4);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 8);
    stmt.setShort(12, (short) 135);
    stmt.setFloat(13, 0.08f);
    stmt.setDouble(14, 0.0008);
    stmt.setFloat(15, 0.08f);
    stmt.setDouble(16, 0.0008);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW9);
    stmt.setString(3, C_VALUE);
    stmt.setString(4, E_VALUE);
    stmt.setInt(5, 9);
    stmt.setDate(6, date == null ? null : new Date(date.getTime() + MILLIS_IN_DAY * 2));
    stmt.setBigDecimal(7, BigDecimal.valueOf(3.3));
    l = Integer.MAX_VALUE + 1L;
    assert (l > Integer.MAX_VALUE);
    stmt.setLong(8, l);
    stmt.setInt(9, 3);
    stmt.setInt(10, 300);
    stmt.setByte(11, (byte) 9);
    stmt.setShort(12, (short) 0);
    stmt.setFloat(13, 0.09f);
    stmt.setDouble(14, 0.0009);
    stmt.setFloat(15, 0.09f);
    stmt.setDouble(16, 0.0009);
    stmt.execute();

    stmt.setString(1, tenantId);
    stmt.setString(2, ROW10);
    stmt.setString(3, B_VALUE);
    stmt.setString(4, B_VALUE);
    stmt.setInt(5, 7);
    // Intentionally null
    stmt.setDate(6, null);
    stmt.setBigDecimal(7, BigDecimal.valueOf(0.1));
    stmt.setLong(8, 5L);
    stmt.setInt(9, 5);
    stmt.setNull(10, Types.INTEGER);
    stmt.setByte(11, (byte) 7);
    stmt.setShort(12, (short) 134);
    stmt.setFloat(13, 0.07f);
    stmt.setDouble(14, 0.0007);
    stmt.setFloat(15, 0.07f);
    stmt.setDouble(16, 0.0007);
    stmt.execute();

    conn.commit();
    return tableName;

}

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

/**
 * This is the core method to set the parameter of a prepared statement to a given value.
 * The primary purpose of this method is to call the appropriate method on the statement,
 * and to give database-specific implementations the ability to change this behavior.
 * /* w w w .  java 2s  . c  om*/
 * @param statement The statement
 * @param sqlIndex  The parameter index
 * @param typeCode  The JDBC type code
 * @param value     The value
 * @throws SQLException If an error occurred while setting the parameter value
 */
protected void setStatementParameterValue(PreparedStatement statement, int sqlIndex, int typeCode, Object value)
        throws SQLException {
    if (value == null) {
        statement.setNull(sqlIndex, typeCode);
    } else if (value instanceof String) {
        statement.setString(sqlIndex, (String) value);
    } else if (value instanceof byte[]) {
        statement.setBytes(sqlIndex, (byte[]) value);
    } else if (value instanceof Boolean) {
        statement.setBoolean(sqlIndex, ((Boolean) value).booleanValue());
    } else if (value instanceof Byte) {
        statement.setByte(sqlIndex, ((Byte) value).byteValue());
    } else if (value instanceof Short) {
        statement.setShort(sqlIndex, ((Short) value).shortValue());
    } else if (value instanceof Integer) {
        statement.setInt(sqlIndex, ((Integer) value).intValue());
    } else if (value instanceof Long) {
        statement.setLong(sqlIndex, ((Long) value).longValue());
    } else if (value instanceof BigDecimal) {
        // setObject assumes a scale of 0, so we rather use the typed setter
        statement.setBigDecimal(sqlIndex, (BigDecimal) value);
    } else if (value instanceof Float) {
        statement.setFloat(sqlIndex, ((Float) value).floatValue());
    } else if (value instanceof Double) {
        statement.setDouble(sqlIndex, ((Double) value).doubleValue());
    } else {
        statement.setObject(sqlIndex, value, typeCode);
    }
}

From source file:edu.ku.brc.specify.toycode.mexconabio.BuildTags.java

/**
 * //from  w w w. j av  a2 s .  c  o m
 */
public void process() throws SQLException {
    int dupAgents = 0;
    int dupLocality = 0;
    int unknown = 0;

    boolean doAll = false;

    BasicSQLUtils.setDBConnection(dbConn);

    boolean doTrim = false;
    if (doTrim || doAll) {
        String trimNamesSQL = "UPDATE tagger SET first=TRIM(first),last=TRIM(last),company=TRIM(company),address1=TRIM(address1),address2=TRIM(address2),city=TRIM(city),state=TRIM(state)";
        BasicSQLUtils.update(srcDBConn2, trimNamesSQL);

        String removeQuote = "UPDATE tagger SET first=SUBSTRING_INDEX(first, '\"', -1),last=SUBSTRING_INDEX(last, '\"', -1),company=SUBSTRING_INDEX(company, '\"', -1),address1=SUBSTRING_INDEX(address1, '\"', -1),"
                + "address2=SUBSTRING_INDEX(address2, '\"', -1),city=SUBSTRING_INDEX(city, '\"', -1), state=SUBSTRING_INDEX(state, '\"', -1)";
        BasicSQLUtils.update(srcDBConn2, removeQuote);

        String trimNamesSQL2 = "UPDATE tag SET city=TRIM(city),county=TRIM(county),state=TRIM(state)";
        BasicSQLUtils.update(srcDBConn2, trimNamesSQL2);

        String removeQuote2 = "UPDATE tag SET city=SUBSTRING_INDEX(city, '\"', -1), county=SUBSTRING_INDEX(county, '\"', -1), state=SUBSTRING_INDEX(state, '\"', -1)";
        BasicSQLUtils.update(srcDBConn2, removeQuote2);
    }

    IdMapperMgr idMapperMgr = IdMapperMgr.getInstance();
    idMapperMgr.setDBs(srcDBConn2, dbConn);

    IdHashMapper agentMapper;

    Division division = (Division) session.get(Division.class, 2);

    initialPrepareStatements();

    BasicSQLUtils.update(srcDBConn, "UPDATE tag SET `Date` = null WHERE Date = '0000-00-00'");

    //IdMapperMgr.setSkippingOldTableCheck(true);

    boolean doAgents = false;
    if (doAgents || doAll) {
        agentMapper = new IdTableMapper("agent", "AgentID", false, false);

        String sql = "SELECT first, last, company, address1, address2, city, state, country, zip, phone, fax, enail, tnum FROM tagger ORDER BY tnum";
        Statement stmt = srcDBConn.createStatement();
        stmt.setFetchSize(Integer.MIN_VALUE);

        log.debug("Querying for Agents...");
        ResultSet rs = stmt.executeQuery(sql);
        int cnt = 0;
        while (rs.next()) {
            String first = rs.getString(1);
            String last = rs.getString(2);
            String company = rs.getString(3);
            String addr1 = rs.getString(4);
            String addr2 = rs.getString(5);
            String city = rs.getString(6);
            String state = rs.getString(7);
            String country = rs.getString(8);
            String zip = rs.getString(9);
            String phone = rs.getString(10);
            String fax = rs.getString(11);
            String email = rs.getString(12);
            Integer oldId = rs.getInt(13);

            if (oldId == null) {
                log.error("Null primary Id: " + last + " " + first);
                continue;
            }

            Agent agent = getAgent(first, last, city, state);
            Integer agentId = null;
            if (agent == null) {
                agent = new Agent();
                agent.initialize();
                agent.setFirstName(first);
                agent.setLastName(last);
                agent.setEmail(email);
                agent.setRemarks(company);
                agent.setDivision(division);

                Address addr = new Address();
                addr.initialize();
                addr.setAddress(addr1);
                addr.setAddress2(addr2);
                addr.setCity(city);
                addr.setState(state);
                addr.setCountry(country);
                addr.setPostalCode(zip);
                addr.setPhone1(phone);
                addr.setFax(fax);

                agent.getAddresses().add(addr);
                addr.setAgent(agent);

                Transaction trans = null;
                try {
                    trans = session.beginTransaction();
                    session.saveOrUpdate(agent);
                    session.saveOrUpdate(addr);
                    trans.commit();

                    agentId = agent.getId();

                } catch (Exception ex) {
                    ex.printStackTrace();
                    try {
                        if (trans != null)
                            trans.rollback();
                    } catch (Exception ex2) {
                        ex2.printStackTrace();
                    }
                }
            } else {
                agentId = agent.getId();
                dupAgents++;
                //System.out.println("Found Agent: "+first+", "+last);
            }
            agentMapper.put(oldId, agentId);

            cnt++;
            if (cnt % 500 == 0) {
                System.out.println("Agents: " + cnt);
            }

            if (cnt % 400 == 0) {
                HibernateUtil.closeSession();
                session = HibernateUtil.getCurrentSession();
                hibSession = new HibernateDataProviderSession(session);
            }
        }
        rs.close();
        stmt.close();

        division = (Division) session.get(Division.class, 2);

    } else {
        //agentMapper = idMapperMgr.addTableMapper("agent", "AgentID", false);
        IdHashMapper.setEnableDelete(false);
        agentMapper = new IdTableMapper("agent", "AgentID", null, false, false);
    }

    System.out.println("Duplicated Agent: " + dupAgents);

    boolean doTags = true;
    if (doTags || doAll) {
        HashMap<String, Integer> localityHash = new HashMap<String, Integer>();
        HashMap<Integer, String> geoFullNameHash = new HashMap<Integer, String>();

        int divId = 2;
        int dspId = 3;
        int colId = 4;

        String sql = "SELECT t.tagid, t.`date`, t.wild, t.gender, t.city, t.county, t.state, t.country, t.zip, t.observations, t.lat, t.lon, t.sunangle, p.tnum "
                + "FROM tag AS t  Inner Join page AS p ON t.page = p.page ";
        Statement stmt = srcDBConn.createStatement();
        stmt.setFetchSize(Integer.MIN_VALUE);

        log.debug("Querying for Tags...");
        ResultSet rs = stmt.executeQuery(sql);
        int cnt = 0;
        log.debug("Done querying for Tags...");

        Calendar cal = Calendar.getInstance();
        Timestamp ts = new Timestamp(cal.getTime().getTime());

        String common = "TimestampCreated, Version, CreatedByAgentID";
        String coStr = String.format(
                "INSERT INTO collectionobject (CatalogNumber, FieldNumber, Text1, Remarks, CollectionID, CollectionMemberId, CollectingEventID, %s) VALUES(?,?,?,?,?,?,?,?,?,?)",
                common);
        String ceStr = String.format(
                "INSERT INTO collectingevent (StartDate, Method, DisciplineID, LocalityID, %s) VALUES(?,?,?,?,?,?,?)",
                common);
        String lcStr = String.format(
                "INSERT INTO locality (Latitude1, Longitude1, SrcLatLongUnit, Lat1text, Long1text, LatLongType, DisciplineID, MaxElevation, LocalityName, GeographyID, %s) VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)",
                common);
        String clStr = String.format(
                "INSERT INTO collector (OrderNumber, IsPrimary, CollectingEventID, DivisionID, AgentID, %s) VALUES(?,?,?,?,?,?,?,?)",
                common);

        PreparedStatement coStmt = dbConn.prepareStatement(coStr);
        PreparedStatement ceStmt = dbConn.prepareStatement(ceStr);
        PreparedStatement lcStmt = dbConn.prepareStatement(lcStr);
        PreparedStatement clStmt = dbConn.prepareStatement(clStr);

        int recNum = 1;
        while (rs.next()) {
            String tag = rs.getString(1);
            if (tag != null && tag.startsWith("ERR"))
                continue;

            Date date = rs.getDate(2);
            String wild = rs.getString(3);
            String gender = rs.getString(4);
            String city = rs.getString(5);
            String county = rs.getString(6);
            String state = rs.getString(7);
            String country = rs.getString(8);
            //String zip     = rs.getString(9);
            String obs = rs.getString(10);
            double lat = rs.getDouble(11);
            double lon = rs.getDouble(12);
            double angle = rs.getDouble(13);
            Integer taggerId = rs.getInt(14);

            String locName = null;
            String fullName = null;

            Integer locId = null;
            Integer geoId = getGeography(country, state, county);
            if (geoId != null) {
                //locName   = localityHash.get(geoId);
                fullName = geoFullNameHash.get(geoId);
                if (fullName == null) {
                    fullName = BasicSQLUtils
                            .querySingleObj("SELECT FullName FROM geography WHERE GeographyID = " + geoId);
                    geoFullNameHash.put(geoId, fullName);
                }

                if (StringUtils.isNotEmpty(city)) {
                    locName = city + ", " + fullName;
                } else {
                    locName = fullName;
                }
                locId = localityHash.get(locName);

            } else {
                unknown++;
                fullName = "Unknown";
                locName = buildLocalityName(city, fullName);
                geoId = 27507; // Unknown
                locId = localityHash.get(locName);
                //log.error("Couldn't find matching geography["+country+", "+state+", "+county+"]");
            }

            if (locId == null) {
                lcStmt.setDouble(1, lat);
                lcStmt.setDouble(2, lon);
                lcStmt.setByte(3, (byte) 0);
                lcStmt.setString(4, Double.toString(lat));
                lcStmt.setString(5, Double.toString(lon));
                lcStmt.setString(6, "Point");
                lcStmt.setInt(7, dspId);
                lcStmt.setDouble(8, angle);
                lcStmt.setString(9, locName);
                lcStmt.setObject(10, geoId);
                lcStmt.setTimestamp(11, ts);
                lcStmt.setInt(12, 1);
                lcStmt.setInt(13, 1);
                lcStmt.executeUpdate();
                locId = BasicSQLUtils.getInsertedId(lcStmt);

                localityHash.put(locName, locId);
            } else {
                dupLocality++;
            }

            // (StartDate, Method, DisciplineID, LocalityID
            ceStmt.setDate(1, date);
            ceStmt.setString(2, wild);
            ceStmt.setInt(3, dspId);
            ceStmt.setInt(4, locId);
            ceStmt.setTimestamp(5, ts);
            ceStmt.setInt(6, 1);
            ceStmt.setInt(7, 1);
            ceStmt.executeUpdate();
            Integer ceId = BasicSQLUtils.getInsertedId(ceStmt);

            //(CatalogNumber, FieldNumber, Text1, Remarks, CollectionID, CollectionMemberId
            coStmt.setString(1, String.format("%09d", recNum++));
            coStmt.setString(2, tag);
            coStmt.setString(3, gender);
            coStmt.setString(4, obs);
            coStmt.setInt(5, colId);
            coStmt.setInt(6, colId);
            coStmt.setInt(7, ceId);
            coStmt.setTimestamp(8, ts);
            coStmt.setInt(9, 1);
            coStmt.setInt(10, 1);
            coStmt.executeUpdate();
            //Integer coId = BasicSQLUtils.getInsertedId(coStmt);

            //Integer coltrId = null;
            if (taggerId != null) {
                Integer agentId = agentMapper.get(taggerId);
                //System.out.println(agentId);
                if (agentId != null) {
                    // OrderIndex, IsPrimary, CollectingEventID, DivisionID, AgentID
                    clStmt.setInt(1, 0);
                    clStmt.setBoolean(2, true);
                    clStmt.setInt(3, ceId);
                    clStmt.setInt(4, divId);
                    clStmt.setInt(5, agentId);
                    clStmt.setTimestamp(6, ts);
                    clStmt.setInt(7, 1);
                    clStmt.setInt(8, 1);
                    clStmt.executeUpdate();
                    //coltrId = BasicSQLUtils.getInsertedId(clStmt);
                    //BasicSQLUtils.getInsertedId(clStmt);

                } else {
                    log.debug("Couldn't find Agent in DB for tagger id (tnum): " + taggerId + "  AgentID:: "
                            + agentId);
                }
            } else {
                log.debug("Couldn't find Mapped Id for tagger id (tnum): " + taggerId);
            }

            cnt++;
            if (cnt % 1000 == 0) {
                System.out.println("Col Obj: " + cnt);
            }
        }

        coStmt.close();
        ceStmt.close();
        lcStmt.close();
        clStmt.close();

        System.out.println("Duplicated Agent:      " + dupAgents);
        System.out.println("Duplicated Localities: " + dupLocality);
        System.out.println("Unknown Localities:    " + unknown);
        System.out.println("Localities:            "
                + BasicSQLUtils.getCountAsInt(dbConn, "SELECT COUNT(*) FROM locality"));
    }
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "INSERT" on the given table and and table prefix for
 * the supplied attributeValues/*  w w  w . ja  v a 2  s  .  co  m*/
 * 
 * @param table
 * @param attributeValues
 * @return
 * @throws SQLException
 */
public boolean insertRow(String table, Map attributeValues) throws SQLException {

    PreparedStatement prepStmt = null;
    Object attribute = null;
    boolean success = false;

    try {
        prepStmt = sqlConnection_.prepareStatement(getSQLTableConstants().getInsertStatementSQL(table));

        for (int i = 0; i < attributeValues.size(); i++) {

            attribute = attributeValues.get("" + (i + 1));

            // If null, we are unable to determine the SQL param type,
            // so String is assumed by default.
            if (attribute == null) {
                prepStmt.setString(i + 1, null);
            } else if (attribute instanceof String) {
                prepStmt.setString(i + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(i + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(i + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(i + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(i + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(i + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(i + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(i + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(i + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(i + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(i + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(i + 1, (Timestamp) attribute);
            }
        }

        success = prepStmt.execute();
    } finally {
        prepStmt.close();
    }

    return success;
}

From source file:org.LexGrid.util.sql.lgTables.SQLTableUtilities.java

/**
 * Runs SQL Statement "UPDATE" on the given tableName with attribute values
 * and where clause./*from  w w  w. j  a v a  2  s . c  o m*/
 * 
 * @param tableName
 * @param attributeNameValue
 * @param whereClause
 * @return
 * @throws SQLException
 */
public int updateRow(String tableName, Map attributeNameValue, String whereClause, String dbType)
        throws SQLException {

    StringBuffer stmt = new StringBuffer();
    PreparedStatement prepStmt = null;
    int rowsUpdated = 0;
    Object attribute = null;
    Iterator itr = null;
    String[] key = new String[attributeNameValue.size()];
    int count = 0;

    stmt.append("UPDATE " + tablePrefix_ + tableName.trim() + " SET ");

    itr = attributeNameValue.keySet().iterator();

    while (itr.hasNext()) {
        key[count] = (String) itr.next();
        stmt.append(key[count++] + " = ?,");
    }

    /*
     * for (int i = 0; i < attributeNames.size(); i++) {
     * stmt.append(attributeNames.get(i) + " = ?,"); }
     */

    stmt = stmt.deleteCharAt(stmt.length() - 1);

    if (whereClause != null && !"".equals(whereClause)) {
        stmt.append(" WHERE ");
        stmt.append(whereClause);
    }

    // stmt = stmt.deleteCharAt(stmt.length());

    log.debug("************ UPDATE QUERY ************");
    log.debug(stmt.toString());
    log.debug("**************************************");
    try {

        String statement = new GenericSQLModifier(dbType, false).modifySQL(stmt.toString());

        prepStmt = sqlConnection_.prepareStatement(statement);

        itr = attributeNameValue.keySet().iterator();

        for (count = 0; count < key.length; count++) {

            attribute = attributeNameValue.get(key[count]);

            if (attribute instanceof String) {
                prepStmt.setString(count + 1, (String) attribute);
            } else if (attribute instanceof Blob) {
                prepStmt.setBlob(count + 1, (Blob) attribute);
            } else if (attribute instanceof Boolean) {
                prepStmt.setBoolean(count + 1, ((Boolean) attribute).booleanValue());
            } else if (attribute instanceof Byte) {
                prepStmt.setByte(count + 1, ((Byte) attribute).byteValue());
            } else if (attribute instanceof byte[]) {
                prepStmt.setBytes(count + 1, (byte[]) attribute);
            } else if (attribute instanceof Date) {
                prepStmt.setDate(count + 1, (Date) attribute);
            } else if (attribute instanceof Double) {
                prepStmt.setDouble(count + 1, ((Double) attribute).doubleValue());
            } else if (attribute instanceof Float) {
                prepStmt.setFloat(count + 1, ((Float) attribute).floatValue());
            } else if (attribute instanceof Integer) {
                prepStmt.setInt(count + 1, ((Integer) attribute).intValue());
            } else if (attribute instanceof Long) {
                prepStmt.setLong(count + 1, ((Long) attribute).longValue());
            } else if (attribute instanceof Short) {
                prepStmt.setShort(count + 1, ((Short) attribute).shortValue());
            } else if (attribute instanceof Timestamp) {
                prepStmt.setTimestamp(count + 1, (Timestamp) attribute);
            }
        }

        rowsUpdated = prepStmt.executeUpdate();
    } catch (Exception e) {
        log.error("Exception @ updateRow: " + e.getMessage());
    } finally {
        prepStmt.close();
    }

    return rowsUpdated;

}

From source file:com.zimbra.cs.db.DbMailItem.java

public static List<Integer> getReIndexIds(DbConnection conn, Mailbox mbox, Set<MailItem.Type> types)
        throws ServiceException {
    List<Integer> ids = new ArrayList<Integer>();
    PreparedStatement stmt = null;
    ResultSet rs = null;//from w  ww .  j ava 2s .co m
    try { // from MAIL_ITEM table
        stmt = conn.prepareStatement("SELECT id FROM " + getMailItemTableName(mbox, false) + " WHERE "
                + IN_THIS_MAILBOX_AND + "index_id IS NOT NULL"
                + (types.isEmpty() ? "" : " AND " + DbUtil.whereIn("type", types.size())));
        int pos = setMailboxId(stmt, mbox, 1);
        for (MailItem.Type type : types) {
            stmt.setByte(pos++, type.toByte());
        }
        rs = stmt.executeQuery();
        while (rs.next()) {
            ids.add(rs.getInt(1));
        }
    } catch (SQLException e) {
        throw ServiceException.FAILURE("Failed to query re-index IDs", e);
    } finally {
        conn.closeQuietly(rs);
        conn.closeQuietly(stmt);
    }
    if (mbox.dumpsterEnabled()) {
        try { // also from MAIL_ITEM_DUMPSTER table
            stmt = conn.prepareStatement("SELECT id FROM " + getMailItemTableName(mbox, true) + " WHERE "
                    + IN_THIS_MAILBOX_AND + "index_id IS NOT NULL"
                    + (types.isEmpty() ? "" : " AND " + DbUtil.whereIn("type", types.size())));
            int pos = setMailboxId(stmt, mbox, 1);
            for (MailItem.Type type : types) {
                stmt.setByte(pos++, type.toByte());
            }
            rs = stmt.executeQuery();
            while (rs.next()) {
                ids.add(rs.getInt(1));
            }
        } catch (SQLException e) {
            throw ServiceException.FAILURE("Failed to query re-index IDs from dumpster", e);
        } finally {
            conn.closeQuietly(rs);
            conn.closeQuietly(stmt);
        }
    }
    return ids;
}

From source file:com.zimbra.cs.db.DbMailItem.java

private static void writeTombstone(Mailbox mbox, MailItem.Type type, String row) throws ServiceException {
    if (Strings.isNullOrEmpty(row)) {
        return;/*  w ww .  j av a2  s  . c  o  m*/
    }

    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    try {
        String mailbox_id = DebugConfig.disableMailboxGroups ? "" : "mailbox_id, ";
        stmt = conn.prepareStatement("INSERT INTO " + getTombstoneTableName(mbox) + "(" + mailbox_id
                + "sequence, date, type, ids)" + " VALUES (" + MAILBOX_ID_VALUE + "?, ?, ?, ?)");
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        stmt.setInt(pos++, mbox.getOperationChangeID());
        stmt.setInt(pos++, mbox.getOperationTimestamp());
        stmt.setByte(pos++, type.toByte());
        stmt.setString(pos++, row);
        stmt.executeUpdate();
    } catch (SQLException e) {
        throw ServiceException.FAILURE("writing tombstones for " + type + "(s): " + row, e);
    } finally {
        DbPool.closeStatement(stmt);
    }
}

From source file:com.zimbra.cs.db.DbMailItem.java

public static List<Integer> listByFolder(Folder folder, MailItem.Type type, boolean descending)
        throws ServiceException {
    Mailbox mbox = folder.getMailbox();/*from   w w  w. ja va 2  s  . c o m*/
    boolean allTypes = type == MailItem.Type.UNKNOWN;
    List<Integer> result = new ArrayList<Integer>();

    DbConnection conn = mbox.getOperationConnection();
    PreparedStatement stmt = null;
    ResultSet rs = null;
    try {
        String typeConstraint = allTypes ? "" : "type = ? AND ";
        stmt = conn.prepareStatement(
                "SELECT id FROM " + getMailItemTableName(folder) + " WHERE " + IN_THIS_MAILBOX_AND
                        + typeConstraint + "folder_id = ?" + " ORDER BY date" + (descending ? " DESC" : ""));
        if (type == MailItem.Type.MESSAGE && folder.getSize() > RESULTS_STREAMING_MIN_ROWS) {
            Db.getInstance().enableStreaming(stmt);
        }
        int pos = 1;
        pos = setMailboxId(stmt, mbox, pos);
        if (!allTypes) {
            stmt.setByte(pos++, type.toByte());
        }
        stmt.setInt(pos++, folder.getId());
        rs = stmt.executeQuery();

        while (rs.next()) {
            result.add(rs.getInt(1));
        }
        return result;
    } catch (SQLException e) {
        throw ServiceException.FAILURE("fetching item list for folder " + folder.getId(), e);
    } finally {
        DbPool.closeResults(rs);
        DbPool.closeStatement(stmt);
    }
}