Example usage for java.sql PreparedStatement setDate

List of usage examples for java.sql PreparedStatement setDate

Introduction

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

Prototype

void setDate(int parameterIndex, java.sql.Date x) throws SQLException;

Source Link

Document

Sets the designated parameter to the given java.sql.Date value using the default time zone of the virtual machine that is running the application.

Usage

From source file:InsertDateToOracle.java

public static void main(String args[]) throws Exception {
    String INSERT_RECORD = "insert into TestDates(id, date_column, "
            + "time_column, timestamp_column) values(?, ?, ?, ?)";
    Connection conn = null;// w ww  . jav  a2s  . c o m
    PreparedStatement pstmt = null;
    try {
        conn = getConnection();
        pstmt = conn.prepareStatement(INSERT_RECORD);
        pstmt.setString(1, "001");

        java.util.Date date = new java.util.Date();
        long t = date.getTime();
        java.sql.Date sqlDate = new java.sql.Date(t);
        java.sql.Time sqlTime = new java.sql.Time(t);
        java.sql.Timestamp sqlTimestamp = new java.sql.Timestamp(t);
        System.out.println("sqlDate=" + sqlDate);
        System.out.println("sqlTime=" + sqlTime);
        System.out.println("sqlTimestamp=" + sqlTimestamp);
        pstmt.setDate(2, sqlDate);
        pstmt.setTime(3, sqlTime);
        pstmt.setTimestamp(4, sqlTimestamp);
        pstmt.executeUpdate();
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("Failed to insert the record.");
    } finally {
        pstmt.close();
        conn.close();
    }
}

From source file:examples.KafkaStreamsDemo.java

public static void main(String[] args) throws InterruptedException, SQLException {
    /**/*from  w  w w . j  a v a2s.  c  o  m*/
     * The example assumes the following SQL schema
     *
     *    DROP DATABASE IF EXISTS beer_sample_sql;
     *    CREATE DATABASE beer_sample_sql CHARACTER SET utf8 COLLATE utf8_general_ci;
     *    USE beer_sample_sql;
     *
     *    CREATE TABLE breweries (
     *       id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       description TEXT,
     *       country VARCHAR(256),
     *       city VARCHAR(256),
     *       state VARCHAR(256),
     *       phone VARCHAR(40),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     *
     *
     *    CREATE TABLE beers (
     *       id VARCHAR(256) NOT NULL,
     *       brewery_id VARCHAR(256) NOT NULL,
     *       name VARCHAR(256),
     *       category VARCHAR(256),
     *       style VARCHAR(256),
     *       description TEXT,
     *       abv DECIMAL(10,2),
     *       ibu DECIMAL(10,2),
     *       updated_at DATETIME,
     *       PRIMARY KEY (id)
     *    );
     */
    try {
        Class.forName("com.mysql.jdbc.Driver");
    } catch (ClassNotFoundException e) {
        System.err.println("Failed to load MySQL JDBC driver");
    }
    Connection connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/beer_sample_sql", "root",
            "secret");
    final PreparedStatement insertBrewery = connection.prepareStatement(
            "INSERT INTO breweries (id, name, description, country, city, state, phone, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " name=VALUES(name), description=VALUES(description), country=VALUES(country),"
                    + " country=VALUES(country), city=VALUES(city), state=VALUES(state),"
                    + " phone=VALUES(phone), updated_at=VALUES(updated_at)");
    final PreparedStatement insertBeer = connection.prepareStatement(
            "INSERT INTO beers (id, brewery_id, name, description, category, style, abv, ibu, updated_at)"
                    + " VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)" + " ON DUPLICATE KEY UPDATE"
                    + " brewery_id=VALUES(brewery_id), name=VALUES(name), description=VALUES(description),"
                    + " category=VALUES(category), style=VALUES(style), abv=VALUES(abv),"
                    + " ibu=VALUES(ibu), updated_at=VALUES(updated_at)");

    String schemaRegistryUrl = "http://localhost:8081";

    Properties props = new Properties();
    props.put(StreamsConfig.APPLICATION_ID_CONFIG, "streams-test");
    props.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "localhost:9092");
    props.put(StreamsConfig.ZOOKEEPER_CONNECT_CONFIG, "localhost:2181");
    props.put(AbstractKafkaAvroSerDeConfig.SCHEMA_REGISTRY_URL_CONFIG, schemaRegistryUrl);
    props.put(StreamsConfig.KEY_SERDE_CLASS_CONFIG, KeyAvroSerde.class);
    props.put(StreamsConfig.VALUE_SERDE_CLASS_CONFIG, ValueAvroSerde.class);

    props.put(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG, "earliest");

    KStreamBuilder builder = new KStreamBuilder();

    KStream<String, GenericRecord> source = builder.stream("streaming-topic-beer-sample");

    KStream<String, JsonNode>[] documents = source.mapValues(new ValueMapper<GenericRecord, JsonNode>() {
        @Override
        public JsonNode apply(GenericRecord value) {
            ByteBuffer buf = (ByteBuffer) value.get("content");
            try {
                JsonNode doc = MAPPER.readTree(buf.array());
                return doc;
            } catch (IOException e) {
                return null;
            }
        }
    }).branch(new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "beer".equals(value.get("type").asText()) && value.has("brewery_id") && value.has("name")
                    && value.has("description") && value.has("category") && value.has("style")
                    && value.has("abv") && value.has("ibu") && value.has("updated");
        }
    }, new Predicate<String, JsonNode>() {
        @Override
        public boolean test(String key, JsonNode value) {
            return "brewery".equals(value.get("type").asText()) && value.has("name") && value.has("description")
                    && value.has("country") && value.has("city") && value.has("state") && value.has("phone")
                    && value.has("updated");
        }
    });
    documents[0].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBeer.setString(1, key);
                insertBeer.setString(2, value.get("brewery_id").asText());
                insertBeer.setString(3, value.get("name").asText());
                insertBeer.setString(4, value.get("description").asText());
                insertBeer.setString(5, value.get("category").asText());
                insertBeer.setString(6, value.get("style").asText());
                insertBeer.setBigDecimal(7, new BigDecimal(value.get("abv").asText()));
                insertBeer.setBigDecimal(8, new BigDecimal(value.get("ibu").asText()));
                insertBeer.setDate(9, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBeer.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });
    documents[1].foreach(new ForeachAction<String, JsonNode>() {
        @Override
        public void apply(String key, JsonNode value) {
            try {
                insertBrewery.setString(1, key);
                insertBrewery.setString(2, value.get("name").asText());
                insertBrewery.setString(3, value.get("description").asText());
                insertBrewery.setString(4, value.get("country").asText());
                insertBrewery.setString(5, value.get("city").asText());
                insertBrewery.setString(6, value.get("state").asText());
                insertBrewery.setString(7, value.get("phone").asText());
                insertBrewery.setDate(8, new Date(DATE_FORMAT.parse(value.get("updated").asText()).getTime()));
                insertBrewery.execute();
            } catch (SQLException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            } catch (ParseException e) {
                System.err.println("Failed to insert record: " + key + ". " + e);
            }
        }
    });

    final KafkaStreams streams = new KafkaStreams(builder, props);
    streams.start();
    Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
        @Override
        public void run() {
            streams.close();
        }
    }));
}

From source file:com.l2jfree.loginserver.tools.L2AccountManager.java

/**
 * Launches the interactive account manager.
 * /*from   w  w  w  . j a v a 2s  . c om*/
 * @param args ignored
 */
public static void main(String[] args) {
    // LOW rework this crap
    Util.printSection("Account Management");

    _log.info("Please choose:");
    //_log.info("list - list registered accounts");
    _log.info("reg - register a new account");
    _log.info("rem - remove a registered account");
    _log.info("prom - promote a registered account");
    _log.info("dem - demote a registered account");
    _log.info("ban - ban a registered account");
    _log.info("unban - unban a registered account");
    _log.info("quit - exit this application");

    BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
    L2AccountManager acm = new L2AccountManager();

    String line;
    try {
        while ((line = br.readLine()) != null) {
            line = line.trim();
            Connection con = null;
            switch (acm.getState()) {
            case USER_NAME:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (!rs.next()) {
                        acm.setUser(line);

                        _log.info("Desired password:");
                        acm.setState(ManagerState.PASSWORD);
                    } else {
                        _log.info("User name already in use.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case PASSWORD:
                try {
                    MessageDigest sha = MessageDigest.getInstance("SHA");
                    byte[] pass = sha.digest(line.getBytes("US-ASCII"));
                    acm.setPass(HexUtil.bytesToHexString(pass));
                } catch (NoSuchAlgorithmException e) {
                    _log.fatal("SHA1 is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                } catch (UnsupportedEncodingException e) {
                    _log.fatal("ASCII is not available!", e);
                    Shutdown.exit(TerminationStatus.ENVIRONMENT_MISSING_COMPONENT_OR_SERVICE);
                }
                _log.info("Super user: [y/n]");
                acm.setState(ManagerState.SUPERUSER);
                break;
            case SUPERUSER:
                try {
                    if (line.length() != 1)
                        throw new IllegalArgumentException("One char required.");
                    else if (line.charAt(0) == 'y')
                        acm.setSuper(true);
                    else if (line.charAt(0) == 'n')
                        acm.setSuper(false);
                    else
                        throw new IllegalArgumentException("Invalid choice.");

                    _log.info("Date of birth: [yyyy-mm-dd]");
                    acm.setState(ManagerState.DOB);
                } catch (IllegalArgumentException e) {
                    _log.info("[y/n]?");
                }
                break;
            case DOB:
                try {
                    Date d = Date.valueOf(line);
                    if (d.after(new Date(System.currentTimeMillis())))
                        throw new IllegalArgumentException("Future date specified.");
                    acm.setDob(d);

                    _log.info("Ban reason ID or nothing:");
                    acm.setState(ManagerState.SUSPENDED);
                } catch (IllegalArgumentException e) {
                    _log.info("[yyyy-mm-dd] in the past:");
                }
                break;
            case SUSPENDED:
                try {
                    if (line.length() > 0) {
                        int id = Integer.parseInt(line);
                        acm.setBan(L2BanReason.getById(id));
                    } else
                        acm.setBan(null);

                    try {
                        con = L2Database.getConnection();
                        PreparedStatement ps = con.prepareStatement(
                                "INSERT INTO account (username, password, superuser, birthDate, banReason) VALUES (?, ?, ?, ?, ?)");
                        ps.setString(1, acm.getUser());
                        ps.setString(2, acm.getPass());
                        ps.setBoolean(3, acm.isSuper());
                        ps.setDate(4, acm.getDob());
                        L2BanReason lbr = acm.getBan();
                        if (lbr == null)
                            ps.setNull(5, Types.INTEGER);
                        else
                            ps.setInt(5, lbr.getId());
                        ps.executeUpdate();
                        _log.info("Account " + acm.getUser() + " has been registered.");
                        ps.close();
                    } catch (SQLException e) {
                        _log.error("Could not register an account!", e);
                    } finally {
                        L2Database.close(con);
                    }
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID or nothing:");
                }
                break;
            case REMOVE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con.prepareStatement("DELETE FROM account WHERE username LIKE ?");
                    ps.setString(1, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been removed.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not remove an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case PROMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, true);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been promoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not promote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case DEMOTE:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET superuser = ? WHERE username LIKE ?");
                    ps.setBoolean(1, false);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been demoted.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case UNBAN:
                acm.setUser(line.toLowerCase());
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setNull(1, Types.INTEGER);
                    ps.setString(2, acm.getUser());
                    int cnt = ps.executeUpdate();
                    if (cnt > 0)
                        _log.info("Account " + acm.getUser() + " has been unbanned.");
                    else
                        _log.info("Account " + acm.getUser() + " does not exist!");
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not demote an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            case BAN:
                line = line.toLowerCase();
                try {
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("SELECT superuser FROM account WHERE username LIKE ?");
                    ps.setString(1, line);
                    ResultSet rs = ps.executeQuery();
                    if (rs.next()) {
                        acm.setUser(line);

                        _log.info("Ban reason ID:");
                        acm.setState(ManagerState.REASON);
                    } else {
                        _log.info("Account does not exist.");
                        acm.setState(ManagerState.INITIAL_CHOICE);
                    }
                    rs.close();
                    ps.close();
                } catch (SQLException e) {
                    _log.error("Could not access database!", e);
                    acm.setState(ManagerState.INITIAL_CHOICE);
                } finally {
                    L2Database.close(con);
                }
                break;
            case REASON:
                try {
                    int ban = Integer.parseInt(line);
                    con = L2Database.getConnection();
                    PreparedStatement ps = con
                            .prepareStatement("UPDATE account SET banReason = ? WHERE username LIKE ?");
                    ps.setInt(1, ban);
                    ps.setString(2, acm.getUser());
                    ps.executeUpdate();
                    _log.info("Account " + acm.getUser() + " has been banned.");
                    ps.close();
                } catch (NumberFormatException e) {
                    _log.info("Ban reason ID:");
                } catch (SQLException e) {
                    _log.error("Could not ban an account!", e);
                } finally {
                    L2Database.close(con);
                }
                acm.setState(ManagerState.INITIAL_CHOICE);
                break;
            default:
                line = line.toLowerCase();
                if (line.equals("reg")) {
                    _log.info("Desired user name:");
                    acm.setState(ManagerState.USER_NAME);
                } else if (line.equals("rem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.REMOVE);
                } else if (line.equals("prom")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.PROMOTE);
                } else if (line.equals("dem")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.DEMOTE);
                } else if (line.equals("unban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.UNBAN);
                } else if (line.equals("ban")) {
                    _log.info("User name:");
                    acm.setState(ManagerState.BAN);
                } else if (line.equals("quit"))
                    Shutdown.exit(TerminationStatus.MANUAL_SHUTDOWN);
                else
                    _log.info("Incorrect command.");
                break;
            }
        }
    } catch (IOException e) {
        _log.fatal("Could not process input!", e);
    } finally {
        IOUtils.closeQuietly(br);
    }
}

From source file:Main.java

public static long[] getEntryExit(Double id, Calendar date, Connection con, PreparedStatement stmt)
        throws Exception {
    stmt.setDate(1, new java.sql.Date(date.getTimeInMillis()));
    // stmt.setDate(2, new java.sql.Date(date.getTimeInMillis()+1000000));
    stmt.execute();//w  w  w.j  a v a2  s .c o m
    ResultSet rs = stmt.getResultSet();
    if (rs != null) {

        if (rs.next()) {
            Timestamp d1 = rs.getTimestamp(1);
            Timestamp d2 = rs.getTimestamp(2);
            if (d1 != null && d2 != null) {
                System.out.println(id + ":" + new SimpleDateFormat("dd/MM/yyyy").format(date.getTime()) + ":"
                        + d1.toString());
                long[] res = new long[] { d1.getTime(), d2.getTime() };
                return res;
            }
        }
        rs.close();
    }
    return null;
}

From source file:org.rti.zcore.dar.report.RegimenChangeReport.java

/**
 * Get ART regimen records (regimen code field) for this period/site
 * @param conn//from w  w  w  . j av  a2  s  . co m
 * @param siteID
 * @param beginDate
 * @param endDate
 * @return
 * @throws ServletException
 */
protected static ResultSet getArtRegimens(Connection conn, int siteID, Date beginDate, Date endDate)
        throws ServletException {

    ResultSet rs = null;

    String dateRange = "AND date_visit >= ? AND date_visit <= ? ";
    if (endDate == null) {
        dateRange = "AND date_visit = ?";
    }

    try {
        if (siteID == 0) {
            String sql = "SELECT encounter.id AS id, date_visit, patient_id, district_patient_id, "
                    + "first_name, surname, encounter.site_id, age_at_first_visit, encounter.created_by AS created_by, "
                    + "regimen.code AS code, age_at_first_visit AS age, encounter.created, "
                    + "regimen.name AS regimen_name, date_started, regimen_change_reason "
                    + "FROM art_regimen, encounter, regimen, patient  " + "WHERE encounter.id = art_regimen.id "
                    + "AND art_regimen.regimen_1 = regimen.id " + "AND encounter.patient_id = patient.id "
                    + dateRange + "ORDER BY created, surname";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
            }
            rs = ps.executeQuery();
        } else {
            String sql = "SELECT encounter.id AS id, date_visit, patient_id, district_patient_id, "
                    + "first_name, surname, encounter.site_id, age_at_first_visit, encounter.created_by AS created_by, "
                    + "regimen.code AS code, age_at_first_visit AS age, encounter.created, "
                    + "regimen.name AS regimen_name, date_started, regimen_change_reason "
                    + "FROM art_regimen, encounter, regimen, patient  " + "WHERE encounter.id = art_regimen.id "
                    + "AND art_regimen.regimen_1 = regimen.id " + "AND encounter.patient_id = patient.id "
                    + dateRange + "AND encounter.site_id = ? " + "ORDER BY date_started DESC";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
                ps.setInt(3, siteID);
            } else {
                ps.setInt(2, siteID);
            }

            rs = ps.executeQuery();
        }
    } catch (Exception ex) {
        log.error(ex);
    }

    return rs;
}

From source file:org.rti.zcore.dar.utils.RegimenUtils.java

/**
 * Get ART regimen records (regimen code field) for this period/site
 * @param conn//w w w  .  jav a 2s .c o  m
 * @param siteID
 * @param beginDate
 * @param endDate
 * @return
 * @throws ServletException
 */
public static ResultSet getArtRegimens(Connection conn, int siteID, Date beginDate, Date endDate)
        throws ServletException {

    ResultSet rs = null;

    String dateRange = "AND date_visit >= ? AND date_visit <= ? ";
    if (endDate == null) {
        dateRange = "AND date_visit = ?";
    }

    try {
        if (siteID == 0) {
            String sql = "SELECT encounter.id AS id, date_visit, patient_id, district_patient_id, "
                    + "first_name, surname, encounter.site_id, age_at_first_visit, encounter.created_by AS created_by, "
                    + "regimen.code AS code, age_at_first_visit AS age, encounter.created "
                    + "FROM art_regimen, encounter, regimen, patient  " + "WHERE encounter.id = art_regimen.id "
                    + "AND art_regimen.regimen_1 = regimen.id " + "AND encounter.patient_id = patient.id "
                    + dateRange + "ORDER BY created, surname";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
            }
            rs = ps.executeQuery();
        } else {
            String sql = "SELECT encounter.id AS id, date_visit, patient_id, district_patient_id, "
                    + "first_name, surname, encounter.site_id, age_at_first_visit, encounter.created_by AS created_by, "
                    + "regimen.code AS code, age_at_first_visit AS age, encounter.created "
                    + "FROM art_regimen, encounter, regimen, patient  " + "WHERE encounter.id = art_regimen.id "
                    + "AND art_regimen.regimen_1 = regimen.id " + "AND encounter.patient_id = patient.id "
                    + dateRange + "AND encounter.site_id = ? " + "ORDER BY created, surname";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
                ps.setInt(3, siteID);
            } else {
                ps.setInt(2, siteID);
            }

            rs = ps.executeQuery();
        }
    } catch (Exception ex) {
        log.error(ex);
    }
    return rs;
}

From source file:org.apache.sqoop.TestExportUsingProcedure.java

public static void insertFunctiontestDatesAndTimes(int id, String msg, final Date date, final Time time)
        throws SQLException {
    insertFunction(id, msg, new SetExtraArgs() {
        @Override/*from  w w w .j a v  a 2 s  .  c  o  m*/
        public void set(PreparedStatement on) throws SQLException {
            on.setDate(3, date);
            on.setTime(4, time);
        }
    });
}

From source file:com.streamsets.pipeline.stage.origin.jdbc.table.BaseTableJdbcSourceIT.java

protected static void setParamsToPreparedStatement(PreparedStatement ps, int paramIdx, int sqlType,
        Object value) throws SQLException {
    switch (sqlType) {
    case Types.DATE:
        ps.setDate(paramIdx, new java.sql.Date(((Date) value).getTime()));
        break;// w  w w .  j av  a2s .com
    case Types.TIME:
        ps.setTime(paramIdx, new java.sql.Time(((Date) value).getTime()));
        break;
    case Types.TIMESTAMP:
        ps.setTimestamp(paramIdx, new java.sql.Timestamp(((Date) value).getTime()));
        break;
    default:
        ps.setObject(paramIdx, value);
    }
}

From source file:org.rti.zcore.dar.dao.SiteStatisticsDAO.java

/**
 *
 * @param conn/* w w w.  j av  a 2 s  . c  om*/
 * @param siteID
 * @param beginDate
 * @param endDate
 * @return
 * @throws ServletException
 * @throws SQLException
 */
public static int getOIPatients(Connection conn, Date beginDate, Date endDate, int siteID)
        throws ServletException, SQLException {

    int count = 0;
    ResultSet rs = null;

    String dateRange = "AND date_visit >= ? AND date_visit <= ? ";
    if (endDate == null) {
        dateRange = "AND date_visit = ?";
    }

    try {
        if (siteID == 0) {
            String sql = "SELECT DISTINCT patient_id " + "FROM encounter e, patient_item pi, item i "
                    + "WHERE e.id = pi.encounter_id " + "AND pi.item_id = i.id "
                    + "AND (i.item_group_id != 1 OR i.item_group_id != 2  OR i.item_group_id != 3) "
                    + dateRange;
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
            }
            rs = ps.executeQuery();
        } else {
            String sql = "SELECT DISTINCT patient_id " + "FROM encounter e, patient_item pi, item i "
                    + "WHERE e.id = pi.encounter_id " + "AND pi.item_id = i.id "
                    + "AND (i.item_group_id != 1 OR i.item_group_id != 2  OR i.item_group_id != 3) " + dateRange
                    + "AND e.site_id = ? ";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setDate(1, beginDate);
            if (endDate != null) {
                ps.setDate(2, endDate);
                ps.setInt(3, siteID);
            } else {
                ps.setInt(2, siteID);
            }
            rs = ps.executeQuery();
        }
    } catch (Exception ex) {
        log.error(ex);
    }

    while (rs.next()) {
        Long patientId = rs.getLong("patient_id");
        Long regimenId = null;
        ResultSet artRs = RegimenUtils.getPatientArtRegimen(conn, patientId);
        while (artRs.next()) {
            regimenId = artRs.getLong("regimenId");
        }
        artRs.close();
        if (regimenId == null) {
            count++;
        }
    }
    rs.close();

    return count;
}

From source file:org.mapbuilderfreq.FrequencyMapClient.java

public static void setLastMapDate(Date lastMapDate) {
    java.sql.Date sqlDate = new java.sql.Date(lastMapDate.getTime());
    try {//w w w.j  a v  a  2  s.  co m
        String updateQuery = "Update public.\"SysParams\" SET \"LastMapDate\" = ? WHERE \"Id\" = 2;";
        PreparedStatement preparedStatement = db.prepareStatement(updateQuery);
        preparedStatement.setDate(1, sqlDate);
        preparedStatement.executeUpdate();

    } catch (SQLException ex) {
        System.err.println("LastMapDate updating failed...");
        System.err.println(ex);
        System.exit(0);
    }
}