public ArrayList<airschedule> getAirschedule() { connect(); ArrayList<airschedule> list = new ArrayList<airschedule>(); try { pstmt = con.prepareStatement(SQL); ResultSet rs = pstmt.executeQuery(); while (rs.next()) { airschedule s = new airschedule(); s.setSchedule_id(rs.getInt("schedule_id")); s.setDeparture_date(rs.getDate("departure_date")); s.setArrival_date(rs.getDate("arrival_date")); s.setDeparture_time(rs.getTime("departure_time")); s.setArrival_time(rs.getTime("arrival_time")); s.setAirline_name(rs.getString("airline_name")); result++; list.add(s); } this.setResult(result); rs.close(); } catch (SQLException e) { e.printStackTrace(); } finally { disconnect(); } return list; }
private static Time getTime(SQLDialect dialect, ResultSet rs, int index) throws SQLException { // SQLite's type affinity needs special care... if (dialect == SQLDialect.SQLITE) { String time = rs.getString(index); if (time != null) { return new Time(parse("HH:mm:ss", time)); } return null; } // Cubrid SQL dates are incorrectly fetched. Reset milliseconds... // See http://jira.cubrid.org/browse/APIS-159 // See https://sourceforge.net/apps/trac/cubridinterface/ticket/140 else if (dialect == CUBRID) { Time time = rs.getTime(index); if (time != null) { Calendar cal = Calendar.getInstance(); cal.setTimeInMillis(time.getTime()); cal.set(Calendar.MILLISECOND, 0); time = new Time(cal.getTimeInMillis()); } return time; } else { return rs.getTime(index); } }
private void loadHores() { horesClase = new java.sql.Time[17]; horesClase_fi = new java.sql.Time[17]; // SQL query hores de les classses // idTipoHoras=1 serien hores de pati (no les empram); String SQL = "SELECT * FROM `" + core_mysqlDB + "`.sig_hores_classe WHERE idTipoHoras=2 ORDER BY codigo asc"; int i = 0; try { Statement st = getMysql().createStatement(); ResultSet rs = getMysql().getResultSet(SQL, st); while (rs != null && rs.next()) { horesClase[i] = rs.getTime("inicio"); horesClase_fi[i] = rs.getTime("fin"); i += 1; } if (rs != null) { rs.close(); st.close(); } } catch (SQLException ex) { Logger.getLogger(getClass().getName()).log(Level.SEVERE, null, ex); } }
/** * CSV出力用モデルを生成 * * @param rs ResultSet * @return created TcdCsvModel * @throws SQLException SQL実行例外 */ private TcdCsvModel __getTcdCsvFromRs(ResultSet rs) throws SQLException { TcdCsvModel bean = new TcdCsvModel(); bean.setUsrSid(rs.getInt("USR_SID")); bean.setUserName(rs.getString("USI_SEI") + " " + rs.getString("USI_MEI")); bean.setTcdDate(UDate.getInstanceTimestamp(rs.getTimestamp("TCD_DATE"))); bean.setTcdIntime(rs.getTime("TCD_INTIME")); bean.setTcdOuttime(rs.getTime("TCD_OUTTIME")); bean.setTcdStrikeIntime(rs.getTime("TCD_STRIKE_INTIME")); bean.setTcdStrikeOuttime(rs.getTime("TCD_STRIKE_OUTTIME")); bean.setTcdBiko(rs.getString("TCD_BIKO")); bean.setTcdStatus(rs.getInt("TCD_STATUS")); bean.setTcdHolkbn(rs.getInt("TCD_HOLKBN")); bean.setTcdHolother(rs.getString("TCD_HOLOTHER")); bean.setTcdHolcnt(rs.getBigDecimal("TCD_HOLCNT")); bean.setTcdChkkbn(rs.getInt("TCD_CHKKBN")); bean.setTcdSoukbn(rs.getInt("TCD_SOUKBN")); bean.setTcdLockFlg(rs.getInt("TCD_LOCK_FLG")); bean.setTcdAuid(rs.getInt("TCD_AUID")); bean.setTcdAdate(UDate.getInstanceTimestamp(rs.getTimestamp("TCD_ADATE"))); bean.setTcdEuid(rs.getInt("TCD_EUID")); bean.setTcdEdate(UDate.getInstanceTimestamp(rs.getTimestamp("TCD_EDATE"))); return bean; }
public void loadDataKehadiran(DefaultTableModel namatabel) throws SQLException { namatabel.getDataVector().removeAllElements(); namatabel.fireTableDataChanged(); sql = "SELECT * tblkehadiran.tanggal, tbl_pegawai.nama, tbl_jabatan.jabatan, tblkehadiran.jmasuk, tblkehadiran.jkeluar " + "FROM tbl_pegawai " + "INNER JOIN tbl_jabatan ON tbl_pegawai.jabatan=tbl_jabatan.idjabatan " + "INNER JOIN tblkehadiran ON tbl_pegawai.idpegawai=tblkehadiran.idpegawai " + "GROUP BY tbl_pegawai.idpegawai " + "ORDER BY tblkehadiran.tanggal desc;"; pst = KoneksiDB.getConnect().prepareStatement(sql); rs = pst.executeQuery(sql); while (rs.next()) { // lakukan penelusuran baris Object[] o = new Object[5]; o[0] = rs.getDate("tanggal"); o[1] = rs.getString("nama"); o[2] = rs.getString("jabatan"); o[3] = rs.getTime("jmasuk"); o[4] = rs.getTime("jkeluar"); namatabel.addRow(o); } rs.close(); pst.close(); }
public static ArrayList<TripViewer> findTripsViewers( String fromCity, String toCity, String date, String lang) { ArrayList<TripViewer> tripViewers = new ArrayList<TripViewer>(); ResultSet resultSet = null; String query = "SELECT trips.Id, s1.name_" + lang + ", s2.name_" + lang + ", trips.departure, trips.arrival, MIN(seats.price), MAX(seats.price) FROM trips, routes, stations s1, stations s2, seats WHERE\n" + " routes.Id = trips.route \n" + " AND\n" + " routes.from_station = s1.Id\n" + " AND \n" + " routes.to_station = s2.Id \n" + " AND\n" + " s1.city = (SELECT Id FROM cities WHERE name_" + lang + " = '" + fromCity + "')\n" + " AND\n" + " s2.city = (SELECT Id FROM cities WHERE name_" + lang + " = '" + toCity + "')" + " AND\n" + " trips.departure >= '" + date + "' AND trips.departure < '" + date + " 23:59:59.997'" + " AND \n" + " seats.trip = trips.Id"; DBWorker dbWorker = new DBWorker(); resultSet = dbWorker.executeQuery(query); try { while (resultSet.next()) { // trips.add(new Trip(resultSet.getInt("Id"))); tripViewers.add( new TripViewer( resultSet.getInt(1), resultSet.getString(2), resultSet.getString(3), resultSet.getDate(4), resultSet.getTime(4), resultSet.getDate(5), resultSet.getTime(5), resultSet.getDouble(6), resultSet.getDouble(7))); } } catch (SQLException e) { e.printStackTrace(); } return tripViewers; }
public static ArrayList<Trip> select(String lang) { ArrayList<Trip> trips = new ArrayList<Trip>(); DBWorker dbWorker = new DBWorker(); ResultSet resultSet = null; String query = "SELECT c1.name_" + lang + ", c1.Id, c2.name_" + lang + ", c2.Id, s1.name_" + lang + ", s1.Id, s2.name_" + lang + ", s2.Id, routes.Id, buses.Id, buses.name_" + lang + ", buses.seats, trips.Id, trips.departure, trips.arrival FROM cities c1, cities c2, stations s1, stations s2, routes, trips, buses WHERE\n" + " routes.from_station = s1.Id \n" + " AND \n" + " routes.to_station = s2.Id \n" + " AND \n" + " s1.city = c1.Id \n" + " AND \n" + " s2.city = c2.Id \n" + " AND \n" + " trips.route = routes.Id \n" + " AND \n" + " trips.bus = buses.Id"; resultSet = dbWorker.executeQuery(query); try { while (resultSet.next()) { City c1 = new City(resultSet.getLong(2), resultSet.getString(1)); City c2 = new City(resultSet.getLong(4), resultSet.getString(3)); Station s1 = new Station(resultSet.getLong(6), c1, resultSet.getString(5)); Station s2 = new Station(resultSet.getLong(8), c2, resultSet.getString(7)); Route route = new Route(resultSet.getLong(9), s1, s2); Bus bus = new Bus(resultSet.getLong(10), resultSet.getString(11), resultSet.getInt(12)); Trip trip = new Trip( resultSet.getLong(13), route, bus, resultSet.getDate(14), resultSet.getTime(14), resultSet.getDate(15), resultSet.getTime(15)); trips.add(trip); } } catch (SQLException e) { e.printStackTrace(); } dbWorker.closeConnection(); return trips; }
public static ArrayList<Evento> get(String select, String complex, ArrayList<String> datos) throws ClassNotFoundException, NumberFormatException, SQLException { Connection con = Conexion.abrirConexion(); ArrayList<Evento> reg = new ArrayList<Evento>(); if (con != null) { ResultSet res = ConsultaSegura.hacerConsulta( con, "select " + select + " from " + tabladb + " " + (complex.equals("") ? " " : complex), datos); while (res.next()) { Evento r = new Evento(); try { r.setTitulo(res.getString("titulo")); } catch (SQLException e) { } try { r.setMensaje(res.getString("mensaje")); } catch (SQLException e) { } try { r.setTieneImagen(res.getBoolean("tiene_imagen")); } catch (SQLException e) { } try { r.setNombreUsuario(res.getString("nombre_usuario")); } catch (SQLException e) { } try { r.setFechaEvento(res.getDate("fecha_evento")); } catch (SQLException e) { } try { r.setHoraInicio(res.getTime("hora_inicio")); } catch (SQLException e) { } try { r.setHoraFin(res.getTime("hora_fin")); } catch (SQLException e) { } r.setId(res.getInt("id")); reg.add(r); } Conexion.cerrarConexion(con); return reg; } else { return null; } }
// Obtains a list of bookings public List<Booking> getBookingList(String staffID) { // TODO: Un-fudge Statement temp = null; String query = "SELECT * FROM Booking"; List<Booking> bookingList = new ArrayList<Booking>(); try { temp = _conn.createStatement(); ResultSet resultSet = temp.executeQuery(query); // Refactored while (resultSet.next()) { String bookingID = resultSet.getString(1); String lectureID = resultSet.getString(2); Time start = resultSet.getTime(3); Date theDate = resultSet.getDate(3); Time end = resultSet.getTime(4); String locationID = resultSet.getString(5); String staffName = resultSet.getString(6); String attListID = resultSet.getString(7); String moduleID = resultSet.getString(8); String moduleName = resultSet.getString(9); String lectType = resultSet.getString(10); String roomNo = resultSet.getString(11); String building = resultSet.getString(12); // Refactoring - initially details within BookingModel, location, module and lecture // now have their own data structures to store info Location thisLocation = new Location(locationID, roomNo, building); Module thisModule = new Module(moduleID, moduleName); Lecture thisLecture = new Lecture(lectureID, moduleID, Lecture.LectType.valueOf(lectType)); // Commented out cos it broke things // Booking thisBooking = new Booking (start, end, theDate, attListID, thisLocation, // thisModule, thisLecture); // bookingList.add(thisBooking); } temp.close(); } catch (Exception e) { // TODO: No results exception } return bookingList; }
/** * Zeige die Daten aller Spiele an, die am ersten Spieltag aller drei Ligen nach 17 Uhr begonnen * haben. * * @param db Hostadresse der Datenbank * @param user Benutzername für Datenbank * @param password Passwort für Datenbank * @throws SQLException Exception für Datenbankzugriffe benötigt * @throws ClassNotFoundException Exception für Postgres-Verbindung benötigt * @see #connect(String, String, String) * @see #disconnect() */ public static void select3(String db, String user, String password) throws SQLException, ClassNotFoundException { connect(db, user, password); System.out.println("Spiele am ersten Spieltag nach 17 Uhr:"); ResultSet rs = stmt.executeQuery("SELECT * FROM bl.spiel WHERE spieltag = 1 AND uhrzeit > '17:00:00';"); while (rs.next()) { int spiel_id = rs.getInt("spiel_id"); int spieltag = rs.getInt("spieltag"); Date datum = rs.getDate("datum"); Time uhrzeit = rs.getTime("uhrzeit"); int heim = rs.getInt("heim"); int gast = rs.getInt("gast"); int tore_heim = rs.getInt("tore_heim"); int tore_gast = rs.getInt("tore_gast"); System.out.print("ID: " + spiel_id + "; \t"); System.out.print("Spieltag: " + spieltag + ";\t"); System.out.print("Datum: " + datum + ";\t"); System.out.print("Uhrzeit: " + uhrzeit + ";\t"); System.out.print("Heim: " + heim + ";\t"); System.out.print("Gast: " + gast + ";\t"); System.out.print("Tore Heim: " + tore_heim + ";\t"); System.out.print("Tore Gast: " + tore_gast + ";"); System.out.println(); } rs.close(); System.out.println(); disconnect(); }
/** * On input from the DB, read the data from the ResultSet into the appropriate type of object to * be stored in the table cell. */ public Object readResultSet(ResultSet rs, int index, boolean limitDataRead) throws java.sql.SQLException { Time data = rs.getTime(index); if (rs.wasNull()) return null; else return data; }
public static void fillTable(String aQuery, JTable aTable, Connector aConnector) throws SQLException { ((DefaultTableModel) aTable.getModel()).setRowCount(0); ((DefaultTableModel) aTable.getModel()).setColumnCount(0); ResultSet results = aConnector.sendQuery(aQuery); ResultSetMetaData metadata = results.getMetaData(); cols = metadata.getColumnCount(); rowData = new Object[cols]; colNames = new String[cols]; for (int i = 0; i < cols; i++) { colNames[i] = metadata.getColumnName(i + 1); } for (int i = 0; i < cols; i++) { ((DefaultTableModel) aTable.getModel()).addColumn(colNames[i]); } while (results.next()) { for (int i = 0; i < cols; i++) { if (metadata.getColumnName(i + 1).equalsIgnoreCase("DatePosted")) { rowData[i] = StrVal.SqlStringToString(results.getDate(i + 1).toString()); rowData[i] += " || "; rowData[i] += results.getTime(i + 1).toString(); } else rowData[i] = results.getString(i + 1); } ((DefaultTableModel) aTable.getModel()).addRow(rowData); } }
private List<WebSocketChannelDTO> buildChannelDTOs(ResultSet rs) throws SQLException { ArrayList<WebSocketChannelDTO> channels = new ArrayList<>(); try { while (rs.next()) { WebSocketChannelDTO channel = new WebSocketChannelDTO(); channel.id = rs.getInt("channel_id"); channel.host = rs.getString("host"); channel.port = rs.getInt("port"); channel.url = rs.getString("url"); channel.startTimestamp = rs.getTimestamp("start_timestamp").getTime(); Time endTs = rs.getTime("end_timestamp"); channel.endTimestamp = (endTs != null) ? endTs.getTime() : null; channel.historyId = rs.getInt("history_id"); channels.add(channel); } } finally { rs.close(); } channels.trimToSize(); return channels; }
public static void getProfile() { String url = "jdbc:mysql://" + var.db_host + "/" + var.db_name; String login = var.db_username; String passwd = var.db_psswd; Connection cn = null; Statement stmt = null; String query = "SELECT * FROM profiles WHERE Name='" + getCurrentProfile() + "'"; try { Class.forName("com.mysql.jdbc.Driver"); cn = DriverManager.getConnection(url, login, passwd); stmt = cn.createStatement(); ResultSet rs = stmt.executeQuery(query); while (rs.next()) { Status.Name = rs.getString("Name"); Status.Sunrise = rs.getTime("Sunrise"); Status.Sunset = rs.getTime("Sunset"); Status.Interval = rs.getTime("Interval"); Status.Working_Time = rs.getTime("Working_Time"); Status.Tank_Capacity = rs.getDouble("Tank_Capacity"); Status.Pump_Flow = rs.getDouble("Pump_Flow"); Status.Watering_Hour = rs.getTime("Watering_Hour"); Status.Water_Amount = rs.getDouble("Water_Amount"); Status.Temperature = rs.getDouble("Temperature"); Status.Humidity = rs.getDouble("Humidity"); Status.Water_Days[0] = rs.getInt("Monday") == 1; Status.Water_Days[1] = rs.getInt("Tuesday") == 1; Status.Water_Days[2] = rs.getInt("Wednesday") == 1; Status.Water_Days[3] = rs.getInt("Thursday") == 1; Status.Water_Days[4] = rs.getInt("Friday") == 1; Status.Water_Days[5] = rs.getInt("Saturday") == 1; Status.Water_Days[6] = rs.getInt("Sunday") == 1; } } catch (SQLException e) { e.printStackTrace(); } catch (ClassNotFoundException e) { e.printStackTrace(); } finally { if (stmt != null) { try { stmt.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
@SuppressWarnings("deprecation") @Test public void time() throws SQLException { connectWithJulianDayModeActivated(); Time d1 = new Time(System.currentTimeMillis()); stat.execute("create table t (c1);"); PreparedStatement prep = conn.prepareStatement("insert into t values (?);"); prep.setTime(1, d1); prep.executeUpdate(); ResultSet rs = stat.executeQuery("select c1 from t;"); assertTrue(rs.next()); assertEquals(d1.getHours(), rs.getTime(1).getHours()); assertEquals(d1.getMinutes(), rs.getTime(1).getMinutes()); assertEquals(d1.getSeconds(), rs.getTime(1).getSeconds()); }
@Override public Time getTime(String name) throws JdbcException { try { return rSet.getTime(name); } catch (SQLException ex) { throw newJdbcException(ex); } }
/** @throws Exception If failed. */ @SuppressWarnings("deprecation") public void testTime() throws Exception { ResultSet rs = stmt.executeQuery(SQL); int cnt = 0; while (rs.next()) { if (cnt == 0) { assert rs.getTime("timeVal").equals(new Time(1, 1, 1)); assert rs.getTime(13).equals(new Time(1, 1, 1)); } cnt++; } assert cnt == 1; }
@Nullable @Override public OffsetTime getValue(ResultSet rs, int startIndex) throws SQLException { Time time = rs.getTime(startIndex, utc()); return time != null ? OffsetTime.ofInstant(Instant.ofEpochMilli(time.getTime()), ZoneOffset.UTC) : null; }
public List<Participer> listerParticipationforEtudiant(String identifiant) { List<Participer> listeParticipationforEtudiant = new ArrayList<Participer>(); try { Connection connection = DataSourceProvider.getDataSource().getConnection(); // Utiliser la connexion PreparedStatement stmt = connection.prepareStatement( "SELECT participer.*, challenge.*, etudiant.*, adresse.* FROM adresse INNER JOIN (challenge INNER JOIN (participer INNER JOIN etudiant ON participer.id_etudiant = etudiant.id_etudiant)ON participer.id_challenge = challenge.id_challenge) ON adresse.id_adr = challenge.id_adresse WHERE participer.id_etudiant = ? ORDER BY challenge.date_challenge DESC"); stmt.setString(1, identifiant); ResultSet results = stmt.executeQuery(); while (results.next()) { Participer participer = new Participer( results.getString("participer.id_etudiant"), results.getString("participer.id_challenge"), results.getString("participer.presence")); participer.setEtudiant( new Etudiant( results.getString("etudiant.id_etudiant"), results.getString("etudiant.nom_etudiant"), results.getString("etudiant.prenom_etudiant"), results.getString("etudiant.classe_etudiant"), results.getString("etudiant.tel_etudiant"), results.getString("etudiant.mail_etudiant"), results.getString("etudiant.photo_etudiant"), results.getBoolean("etudiant.cotisation_etudiant"), results.getBoolean("etudiant.certificat_etudiant"), results.getString("licence_etudiant"))); participer.setChallenge( new Challenge( results.getString("challenge.id_challenge"), results.getString("challenge.nom_challenge"), results.getDate("challenge.date_challenge"), results.getTime("challenge.heure_challenge"), results.getString("challenge.description_challenge"), results.getString("challenge.id_adresse"))); participer .getChallenge() .setAdresse( new Adresse( results.getString("adresse.id_adr"), results.getString("adresse.site_adr"), results.getString("adresse.num_adr"), results.getString("adresse.rue_adr"), results.getString("adresse.cp_adr"), results.getString("adresse.ville_adr"), results.getString("adresse.pays_adr"))); listeParticipationforEtudiant.add(participer); } // Fermer la connexion results.close(); stmt.close(); connection.close(); } catch (SQLException e) { e.printStackTrace(); } return listeParticipationforEtudiant; }
@Override public Time getTime(int columnIndex) throws SQLException { try { return _res.getTime(columnIndex); } catch (SQLException e) { handleException(e); return null; } }
@Override public Time getTime(String columnName) throws SQLException { try { return _res.getTime(columnName); } catch (SQLException e) { handleException(e); return null; } }
/** * Read a value from a result set. * * @param config the configuration * @param rs the result set * @param index the column index * @return the value */ static Value read(TestSynth config, ResultSet rs, int index) throws SQLException { ResultSetMetaData meta = rs.getMetaData(); Object data; int type = meta.getColumnType(index); switch (type) { case Types.REAL: case Types.DOUBLE: data = rs.getDouble(index); break; case Types.BIGINT: data = rs.getLong(index); break; case Types.DECIMAL: case Types.NUMERIC: data = rs.getBigDecimal(index); break; case Types.BLOB: case Types.BINARY: case Types.VARBINARY: case Types.LONGVARBINARY: data = rs.getBytes(index); break; case Types.OTHER: case Types.CLOB: case Types.VARCHAR: case Types.LONGVARCHAR: case Types.CHAR: data = rs.getString(index); break; case Types.DATE: data = rs.getDate(index); break; case Types.TIME: data = rs.getTime(index); break; case Types.TIMESTAMP: data = rs.getTimestamp(index); break; case Types.INTEGER: data = rs.getInt(index); break; case Types.NULL: data = null; break; case Types.BOOLEAN: case Types.BIT: data = rs.getBoolean(index) ? "TRUE" : "FALSE"; break; default: throw new AssertionError("type=" + type); } if (rs.wasNull()) { data = null; } return new Value(config, type, data); }
public LocationRecord(ResultSet rs) throws SQLException { String imsi = rs.getString("IMSI"); int siteId = rs.getInt("SiteId"); Calendar c = Calendar.getInstance(); c.setTime(rs.getTime("ConnectTime")); int hour = c.get(Calendar.HOUR_OF_DAY); int longitude = rs.getInt("Longitude"); int latitude = rs.getInt("Latitude"); init(imsi, siteId, hour, longitude, latitude); }
@Test public void updateTask() throws Exception { // update existing task Task t = new Task(); Long id = PermanentUserData.tasks.get(0).getId(); t.setName("updated"); t.setRole(new Role(PermanentUserData.tasks.get(0).getRole().getId())); given() .contentType("application/json") .filter(sessionFilter) .body(om.writeValueAsString(t)) .put("/web/" + id.toString()) .then() .statusCode(204); // delete it given() .header(PermanentUserData.tokenHeader) .delete("/m/" + PermanentUserData.tasks.get(0).getId()) .then() .statusCode(204); // test if is recreated with correct values t.setNote("note"); LocalTime moment = LocalTime.now(); int minutes = moment.getMinute(); int hours = moment.getHour(); t.setTime(moment); given() .contentType("application/json") .header(PermanentUserData.tokenHeader) .body(om.writeValueAsString(t)) .put("/m/" + id.toString()) .then() .statusCode(204); try (Connection conn = ds.getConnection(); PreparedStatement ps = conn.prepareStatement("select * from task where name = ?"); ) { ps.setString(1, "updated"); try (ResultSet rs = ps.executeQuery(); ) { rs.next(); assertThat(rs.getString("name"), equalTo("updated")); assertThat(rs.getString("note"), equalTo("note")); assertThat(rs.getTime("time").getMinutes(), equalTo(minutes)); assertThat(rs.getTime("time").getHours(), equalTo(hours)); // rest was set to default assertThat(rs.getBoolean("finished"), equalTo(false)); assertThat(rs.getBoolean("important"), equalTo(false)); assertThat(rs.getBoolean("finished"), equalTo(false)); assertThat(rs.getDate("date"), equalTo(null)); assertThat(rs.getDate("firstDate"), equalTo(null)); } } }
/** * Get value from given ResultSet at given index with given SQL type. * * @param rs The ResultSet to get the value from. * @param index The index of the value in the ResultSet. * @param sqlType The SQL type of the value. * @return The value. * @throws SQLException If a database access error occurs. */ public static Object getValue(final ResultSet rs, final int index, final int sqlType) throws SQLException { switch (sqlType) { case Types.CHAR: case Types.VARCHAR: case Types.LONGVARCHAR: return rs.getString(index); case Types.DECIMAL: case Types.NUMERIC: return rs.getBigDecimal(index); case Types.INTEGER: int intVal = rs.getInt(index); return (rs.wasNull() ? null : new Integer(intVal)); case Types.TIME: return rs.getTime(index, getCalendar()); case Types.DATE: return rs.getDate(index); case Types.TIMESTAMP: return rs.getTimestamp(index, getCalendar()); case Types.FLOAT: case Types.DOUBLE: double doubleVal = rs.getDouble(index); return (rs.wasNull() ? null : new Double(doubleVal)); case Types.REAL: float floatVal = rs.getFloat(index); return (rs.wasNull() ? null : new Float(floatVal)); case Types.SMALLINT: short shortVal = rs.getShort(index); return (rs.wasNull() ? null : new Short(shortVal)); case Types.TINYINT: byte byteVal = rs.getByte(index); return (rs.wasNull() ? null : new Byte(byteVal)); case Types.LONGVARBINARY: case Types.VARBINARY: case Types.BINARY: return rs.getBytes(index); case Types.BLOB: Blob blob = rs.getBlob(index); return (blob == null ? null : blob.getBinaryStream()); case Types.CLOB: return rs.getClob(index); case Types.BIGINT: long longVal = rs.getLong(index); return (rs.wasNull() ? null : new Long(longVal)); case Types.BIT: boolean boolVal = rs.getBoolean(index); return (rs.wasNull() ? null : new Boolean(boolVal)); default: Object value = rs.getObject(index); return (rs.wasNull() ? null : value); } }
@Test public void testAjoutCreneau() throws SQLException, IOException, ClassNotFoundException { Connection connection = BddConnecteur.getConnection(); BddUtilisateur.ajout("*****@*****.**", "labri"); BddLabo.ajout(1, "Labri"); BddAtelier.ajoutAtelier( 1, "A la poursuite d'ennemis invisibles", "Sciences de la vie ", "Campus Carreire (Hôpital Pellegrin)", "Labo MFP", "", "", "", ""); // Insertion int idAtelier = 1; String jour = "2015-12-23"; String heure = "13:00"; int capacite = 20; BddCreneau.ajoutCreneau(1, jour, heure, capacite); // Vérification String sql = "SELECT * FROM Creneau WHERE idAtelier='" + idAtelier + "'"; Statement statement = connection.createStatement(); ResultSet rs = statement.executeQuery(sql); int count = 0; Date jourRecup; Time heureRecup; int capaciteRecup = 0; while (rs.next()) { jourRecup = rs.getDate("jour"); heureRecup = rs.getTime("heure"); capaciteRecup = rs.getInt("capacite"); count++; } assertEquals(count, 1); // assertEquals(jourRecup, jour); // assertEquals(heureRecup, heure); assertEquals(capaciteRecup, capacite); // Fermeture rs.close(); statement.close(); connection.close(); }
/** * Gets a value from a given column in a JDBC result set. * * @param i Ordinal of column (1-based, per JDBC) */ private Object value(int i) throws SQLException { // MySQL returns timestamps shifted into local time. Using // getTimestamp(int, Calendar) with a UTC calendar should prevent this, // but does not. So we shift explicitly. switch (types[i]) { case Types.TIMESTAMP: return shift(resultSet.getTimestamp(i + 1)); case Types.TIME: return shift(resultSet.getTime(i + 1)); case Types.DATE: return shift(resultSet.getDate(i + 1)); } return primitives[i].jdbcGet(resultSet, i + 1); }
/** * 根据商品编码从表promotion里查询出商品的单品促销信息 * * @param connection 到数据库的连接 * @param code 商品编码 * @return 普通促销信息 * @throws SQLException */ public DiscCriteria getDISCTIME(Connection connection, String code) throws SQLException { DiscCriteria result = null; SimpleDateFormat fmt1 = new SimpleDateFormat("HHmmss"); String sql = " SELECT vgno,time1,time2,time3,time4,time5,time6, " + " distrate1,distrate2,distrate3,distrate4,distrate5,distrate6 " + "FROM vgnodiscount where vgno=? and convert(char(8),getdate(),112) between convert(char(8),startdate,112) and convert(char(8),enddate,112); "; PreparedStatement stmt = connection.prepareStatement(sql); stmt.setString(1, code); ResultSet rs = stmt.executeQuery(); if (rs.next()) { String vgno = Formatter.mytrim(rs.getString("vgno")); // int time1 = Integer.parseInt(fmt1.format(Date.valueOf(rs.getString("time1")))); int time1 = Integer.parseInt(fmt1.format(rs.getTime("time1"))); int time2 = Integer.parseInt(fmt1.format(rs.getTime("time2"))); int time3 = Integer.parseInt(fmt1.format(rs.getTime("time3"))); int time4 = Integer.parseInt(fmt1.format(rs.getTime("time4"))); int time5 = Integer.parseInt(fmt1.format(rs.getTime("time5"))); int time6 = Integer.parseInt(fmt1.format(rs.getTime("time6"))); int distrate1 = rs.getInt("distrate1"); int distrate2 = rs.getInt("distrate2"); int distrate3 = rs.getInt("distrate3"); int distrate4 = rs.getInt("distrate4"); int distrate5 = rs.getInt("distrate5"); int distrate6 = rs.getInt("distrate6"); result = new DiscTime( vgno, time1, distrate1, time2, distrate2, time3, distrate3, time4, distrate4, time5, distrate5, time6, distrate6); } return result; }
// 用于修改的查询 public Flight queryM(Flight flight2) { Flight flight = null; String sql = "select * from flight where id=" + flight2.getId() + ""; System.out.println("修改时的SQL:" + sql); ResultSet rs = conn.executeQuery(sql); try { while (rs.next()) { flight = new Flight(); flight.setId(rs.getString(1)); flight.setGoTime(rs.getTime(2)); flight.setReachTime(rs.getTime(3)); flight.setType(rs.getString(4)); flight.setReachAirport(new Airport()); flight.getReachAirport().setId(rs.getInt(5)); flight.setGoAirport(new Airport()); flight.getGoAirport().setId(rs.getInt(6)); flight.setCompany(new Company()); flight.getCompany().setId(rs.getInt(7)); } } catch (SQLException ex) { } conn.close(); return flight; }
public ArrayList<BeanHoraCentro> getHorasClase(String condition) { if (condition == null || condition.isEmpty()) { return getHorasClase(); } ArrayList<BeanHoraCentro> list = new ArrayList<BeanHoraCentro>(); String SQL1 = "SELECT * FROM horasCentro where " + condition + " order by inicio"; try { Statement st = getSgd().createStatement(); ResultSet rs1 = getSgd().getResultSet(SQL1, st); while (rs1 != null && rs1.next()) { list.add(new BeanHoraCentro(rs1.getInt("id"), rs1.getTime("inicio"), rs1.getTime("fin"))); } if (rs1 != null) { rs1.close(); st.close(); } } catch (SQLException ex) { Logger.getLogger(HoraCentro.class.getName()).log(Level.SEVERE, null, ex); } return list; }