Java Code Examples for java.sql.ResultSet.getDate()

The following are Jave code examples for showing how to use getDate() of the java.sql.ResultSet class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: calcite-avatica   File: AvaticaResultSetConversionsTest.java   View Source Code Vote up 6 votes
public void testGetDate(ResultSet resultSet, Calendar calendar) throws SQLException {
  try {
    resultSet.getDate(ordinal, calendar);
    fail("Was expecting to throw SQLDataException");
  } catch (Exception e) {
    assertThat(e, isA((Class) SQLDataException.class)); // success
  }
}
 
Example 2
Project: morf   File: ResultSetComparer.java   View Source Code Vote up 6 votes
@SuppressWarnings("rawtypes")
private Comparable columnToValue(ResultSet resultSet, int columnIndex, int columnType) throws SQLException {
  if (columnTypeIsString(columnType)) {
    return resultSet.getString(columnIndex);
  } else if (columnTypeIsNumeric(columnType)) {
    BigDecimal bigDecimal = resultSet.getBigDecimal(columnIndex);
    return bigDecimal == null ? null : bigDecimal.stripTrailingZeros();
  } else if (columnTypeIsBoolean(columnType)) {
    return resultSet.getBoolean(columnIndex);
  } else if (columnTypeIsDate(columnType)) {
    return resultSet.getDate(columnIndex);
  } else {
    throw new IllegalArgumentException("Column type " + columnType + " not supported for comparison");
  }
}
 
Example 3
Project: Java-Air-Reservation   File: Passenger.java   View Source Code Vote up 6 votes
/**
 * constructor with the id
 * @param passNo : passport number 
 */
public  Passenger(String passNo){
    conn = DBConnect.connect();
    PreparedStatement pst;
    try {
        String sql = "SELECT * FROM `passenger` WHERE `pass_no`=?";
        pst=conn.prepareStatement(sql);
        pst.setString(1,passNo);
        ResultSet rs;
        rs = pst.executeQuery();
        if (!rs.isBeforeFirst() ) {     
            return;
        } 
        while (rs.next()) {
                this.tel = rs.getString("tel");
                this.paddress = rs.getString("paddress");
                this.fname = rs.getString("fname");
                this.lname = rs.getString("lname");
                this.pass_no = rs.getString("pass_no");
                this.password = rs.getString("password");
                this.dob = rs.getDate("dob");
                this.active  = rs.getBoolean("active");
                this.exist = true;
        }
    } catch (SQLException e) {
        System.out.println("Error : while excicuting prepared statement");
        System.out.println(e);
        System.out.println(e.getErrorCode());
    }
}
 
Example 4
Project: morpheus-core   File: SQLExtractor.java   View Source Code Vote up 6 votes
@Override
@SuppressWarnings("unchecked")
public <V> V getValue(ResultSet rs, int colIndex) throws SQLException {
    if (getPlatform() == SQLPlatform.SQLITE) {
        final String value = rs.getString(colIndex);
        if (value == null) {
            return null;
        } else if (value.matches("\\d+")) {
            return (V)Instant.ofEpochMilli(Long.parseLong(value)).atZone(GMT).toLocalDate();
        } else {
            return (V)LocalDate.parse(value);
        }
    } else {
        final java.sql.Date date = rs.getDate(colIndex);
        return date != null ? (V)date.toLocalDate() : null;
    }
}
 
Example 5
Project: scorekeeperfrontend   File: Event.java   View Source Code Vote up 6 votes
public Event(ResultSet rs) throws SQLException
{
	super(rs);
	eventid     = (UUID)rs.getObject("eventid");
	name        = rs.getString("name");
	date        = rs.getDate("date");
	regopened   = rs.getTimestamp("regopened", Database.utc);
	regclosed   = rs.getTimestamp("regclosed", Database.utc);
	courses     = rs.getInt("courses");
	runs		= rs.getInt("runs");
	countedruns = rs.getInt("countedruns");
	segments    = rs.getInt("segments");
	perlimit 	= rs.getInt("perlimit");
	totlimit 	= rs.getInt("totlimit");
	conepen     = rs.getDouble("conepen");
	gatepen 	= rs.getDouble("gatepen");
	ispro       = rs.getBoolean("ispro");
	ispractice  = rs.getBoolean("ispractice");
}
 
Example 6
Project: NotifyTools   File: JDBCDynaClass.java   View Source Code Vote up 5 votes
/**
 * Get a column value from a {@link ResultSet} for the specified name.
 *
 * @param resultSet The result set
 * @param name The property name
 * @return The value
 * @throws SQLException if an error occurs
 */
protected Object getObject(final ResultSet resultSet, final String name) throws SQLException {

    final DynaProperty property = getDynaProperty(name);
    if (property == null) {
        throw new IllegalArgumentException("Invalid name '" + name + "'");
    }
    final String columnName = getColumnName(name);
    final Class<?> type = property.getType();

    // java.sql.Date
    if (type.equals(Date.class)) {
        return resultSet.getDate(columnName);
    }

    // java.sql.Timestamp
    if (type.equals(Timestamp.class)) {
        return resultSet.getTimestamp(columnName);
    }

    // java.sql.Time
    if (type.equals(Time.class)) {
        return resultSet.getTime(columnName);
    }

    return resultSet.getObject(columnName);
}
 
Example 7
Project: mm-system-2017   File: DataAccess.java   View Source Code Vote up 5 votes
@Override
public ArrayList<Mentor> getAllMentorsWithoutMentees() throws SQLException {
	Mentor u = null;
	ArrayList<Mentor> mentorList = new ArrayList<Mentor>();
	Statement stm = c.createStatement();
	stm.executeQuery(SQLStatements.getAllMentorsWithoutMentees);
	ResultSet r = stm.getResultSet();
	while (r.next()) {
		City city = getCityById(r.getInt(DataContract.UsersTable.COL_CITYID));
		Area area = getAreaById(r.getInt(DataContract.UsersTable.COL_AREAID));
		u = new Mentor(r.getInt(DataContract.UsersTable.COL_ID), r.getString(DataContract.UsersTable.COL_FIRSTNAME),
				r.getString(DataContract.UsersTable.COL_LASTNAME), r.getString(DataContract.UsersTable.COL_EMAIL),
				r.getString(DataContract.UsersTable.COL_PHONENUMBER),
				r.getString(DataContract.UsersTable.COL_PASSWORD), r.getInt(DataContract.UsersTable.COL_GENDER),
				r.getString(DataContract.UsersTable.COL_ADDRESS), r.getString(DataContract.UsersTable.COL_NOTES),
				r.getString(DataContract.UsersTable.COL_PROFILEPICTURE),
				r.getBoolean(DataContract.UsersTable.COL_ACTIVE), userType.MENTOR,
				r.getInt(DataContract.UsersTable.COL_AREAID), area.getName(),
				r.getInt(DataContract.UsersTable.COL_CITYID), city.getName(),
				r.getDate(DataContract.UsersTable.COL_JOINDATE),
				r.getString(DataContract.MentorsTable.COL_EXPERIENCE),
				r.getString(DataContract.MentorsTable.COL_ROLE), r.getInt(DataContract.MentorsTable.COL_COMPANY),
				r.getString(DataContract.MentorsTable.COL_VOLUNTEERING),
				r.getString(DataContract.MentorsTable.COL_WORKHISTORY));
		mentorList.add(u);
	}

	r.close();
	stm.close();

	return mentorList;
}
 
Example 8
Project: tangyuan2   File: DateOnlyTypeHandler.java   View Source Code Vote up 5 votes
@Override
public Date getNullableResult(ResultSet rs, String columnName) throws SQLException {
	java.sql.Date sqlDate = rs.getDate(columnName);
	if (sqlDate != null) {
		return new java.util.Date(sqlDate.getTime());
	}
	return null;
}
 
Example 9
Project: nihonGO   File: DatabaseHandler.java   View Source Code Vote up 5 votes
public TestDia getPreguntas(){
    TestDia testdia = new TestDia();
    String enunciado, respuesta, opcion1, opcion2;
    int codigo, nivel;
    Date fecha;
    Pregunta pregunta;       
    
    try{
        ResultSet rs;
        rs =stmt.executeQuery("SELECT * FROM testd");
        while (rs.next()){
            codigo = rs.getInt("codigo");
            enunciado = rs.getString("enunciado");
            respuesta = rs.getString("respuesta");
            opcion1 = rs.getString("opcion1");
            opcion2 = rs.getString("opcion2");
            nivel = rs.getInt("nivel");
            fecha = rs.getDate("fecha");
            pregunta = new Pregunta(codigo, enunciado, respuesta, opcion1, opcion2, nivel, fecha);
            testdia.add(pregunta);
        }        
    }
    catch(SQLException e){
        
    }
    return testdia;
}
 
Example 10
Project: uavstack   File: DAOFactory.java   View Source Code Vote up 5 votes
public Object getResult(ResultSet rs, int columnIndex) throws SQLException {

            Object sqlDate = rs.getDate(columnIndex);
            if (rs.wasNull()) {
                return null;
            }
            else {
                return sqlDate;
            }
        }
 
Example 11
Project: OpenDiabetes   File: TestDatetimeSimple.java   View Source Code Vote up 4 votes
public void testValues() throws SQLException {

        TestUtil.deleteDatabase("/hsql/tests/testdatetimesimple");

        Connection conn = DriverManager.getConnection(connectionURL, "SA", "");
        ResultSet          rs;
        PreparedStatement  ps;
        String             s;
        Object             o;
        java.sql.Date      d;
        java.sql.Timestamp ts;
        Statement          st = conn.createStatement();

        st.executeUpdate("SET TIME ZONE INTERVAL '-5:00' HOUR TO MINUTE");
        st.executeUpdate("DROP TABLE t3 IF EXISTS");
        st.executeUpdate("CREATE TABLE t3(d date)");
        st.executeUpdate("INSERT INTO t3 VALUES('2008-11-27')");

        rs = st.executeQuery("SELECT d FROM t3");

        rs.next();

        s  = rs.getString("d");
        o  = rs.getObject("d");
        d  = rs.getDate("d");
        ts = rs.getTimestamp("d");

        System.out.println("2008-11-27 INSERTED" + "\n    String: " + s
                           + "\n    Object: " + o + "\n    Date: " + dump(d)
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();
        st.executeUpdate("DROP TABLE ts IF EXISTS");
        st.executeUpdate(
            "CREATE TABLE ts(id integer generated by default as identity (start with 1), ts timestamp, tsz timestamp with time zone)");
        st.executeUpdate(
            "INSERT INTO ts VALUES DEFAULT, LOCALTIMESTAMP, CURRENT_TIMESTAMP");

        rs = st.executeQuery("CALL CURRENT_DATE");

        rs.next();

        o  = rs.getObject(1);
        d  = rs.getDate(1);
        s  = rs.getString(1);
        ts = rs.getTimestamp(1);

        System.out.println("CURRENT_DATE @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Date: " + dump(d) + "\n    Timestamp: "
                           + dump(ts) + '\n');
        rs.close();

        rs = st.executeQuery("CALL LOCALTIMESTAMP");

        rs.next();

        o  = rs.getObject(1);
        s  = rs.getString(1);
        ts = rs.getTimestamp(1);

        System.out.println("LOCALTIMESTAMP @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();

        rs = st.executeQuery("CALL CURRENT_TIMESTAMP");

        rs.next();

        s  = rs.getString(1);
        o  = rs.getObject(1);
        ts = rs.getTimestamp(1);

        System.out.println("CURRENT_TIMESTAMP @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();
        st.executeUpdate("SHUTDOWN");
        conn.close();
    }
 
Example 12
Project: JPA-Demo   File: SQLSearch.java   View Source Code Vote up 4 votes
public static void main(String args[]) {
	try {
		// Open database connection
		Class.forName("org.sqlite.JDBC");
		Connection c = DriverManager.getConnection("jdbc:sqlite:./db/company.db");
		c.createStatement().execute("PRAGMA foreign_keys=ON");
		System.out.println("Database connection opened.");
		
		BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
		System.out.print("Name of the employee to be shown: ");
		String searchName = reader.readLine();

		// Retrieve data: begin
		String sql = "SELECT * FROM employees WHERE name LIKE ?";
		PreparedStatement prep = c.prepareStatement(sql);
		prep.setString(1, searchName);
		ResultSet rs = prep.executeQuery();
		while (rs.next()) {
			int id = rs.getInt("id");
			String name = rs.getString("name");
			Date dob = rs.getDate("dob");
			String address = rs.getString("address");
			Double salary = rs.getDouble("salary");
			byte[] photo = rs.getBytes("photo");
			// Note that department is going to show null, even if the
			// employee is assigned to one, that's because we didn't
			// retrieve the department from the database. We should!!
			Employee employee = new Employee(id, name, dob, address, salary, photo);
			System.out.println(employee);
			// Process the photo
			if (photo!=null) {
				ByteArrayInputStream blobIn = new ByteArrayInputStream(employee.getPhoto());
				// Show the photo
				if (showImage) {
					ImageWindow window = new ImageWindow();
					window.showBlob(blobIn);
				}
				// Write the photo in a file
				else {
					File outFile = new File("./photos/Output.png");
					OutputStream blobOut = new FileOutputStream(outFile);
					byte[] buffer = new byte[blobIn.available()];
					blobIn.read(buffer);
					blobOut.write(buffer);
					blobOut.close();
				}
			}
		}
		rs.close();
		prep.close();
		System.out.println("Search finished.");
		// Retrieve data: end
	    
		// Close database connection
		c.close();
		System.out.println("Database connection closed.");
	} catch (Exception e) {
		e.printStackTrace();
	}
}
 
Example 13
Project: mm-system-2017   File: DataAccess.java   View Source Code Vote up 4 votes
@SuppressWarnings("resource") // got warning about stm in case 3 not being closed
@Override
public ArrayList<Meeting> getUserMeetings(int id) throws SQLException {
	ArrayList<Meeting> meeting = new ArrayList<Meeting>();
	Meeting meet = null;
	PreparedStatement stm = c.prepareStatement(SQLStatements.selectUserById);
	stm.setInt(1, id);
	ResultSet rs = stm.executeQuery();

	if (rs.next()) {
		int type = rs.getInt(DataContract.UsersTable.COL_TYPE);
		switch (type) {
		case 2:// Mentor
			stm = c.prepareStatement(SQLStatements.selectMeetingsByMentorId);
			break;
		case 3:// Mentee
			stm = c.prepareStatement(SQLStatements.selectMeetingsByMenteeId);
			break;
		default:
			// TODO: LOG ERROR
			rs.close();
			stm.close();

			return null;
		}
	}

	stm.setInt(1, id);
	rs = stm.executeQuery();
	while (rs.next()) {
		java.sql.Date SDate = rs.getDate(DataContract.MeetingTable.COL_DATE);
		meet = new Meeting(rs.getInt(DataContract.MeetingTable.COL_ACTIVITYID),
				rs.getInt(DataContract.MeetingTable.COL_PAIRID), rs.getInt(DataContract.MeetingTable.COL_MENTORID),
				rs.getInt(DataContract.MeetingTable.COL_MENTEEID), rs.getString(DataContract.MeetingTable.COL_NOTE),
				meetingStatus.valueOf(rs.getInt(DataContract.MeetingTable.COL_STATUS)),
				rs.getString(DataContract.MeetingTable.COL_MENTEEREPORT),
				rs.getString(DataContract.MeetingTable.COL_MENTORREPORT),
				rs.getString(DataContract.MeetingTable.COL_MENTEEPRIVREPORT),
				rs.getString(DataContract.MeetingTable.COL_MENTORPRIVREPORT),
				meetingType.getByValue(rs.getInt(DataContract.MeetingTable.COL_MEETINGTYPE)),
				rs.getString(DataContract.MeetingTable.COL_SUBJECT),
				rs.getString(DataContract.MeetingTable.COL_LOCATION), SDate.getTime(),
				rs.getTime(DataContract.MeetingTable.COL_STARTINGTIME),
				rs.getTime(DataContract.MeetingTable.COL_ENDINGTIME),
				rs.getBoolean(DataContract.MeetingTable.COL_MENTORCOMPLETE),
				rs.getBoolean(DataContract.MeetingTable.COL_MENTEECOMPLETE));
		meeting.add(meet);

	}
	rs.close();
	stm.close();

	return meeting;
}
 
Example 14
Project: morpheus-core   File: SQLExtractor.java   View Source Code Vote up 4 votes
@Override
@SuppressWarnings("unchecked")
public <V> V getValue(ResultSet rs, int colIndex) throws SQLException {
    return (V)rs.getDate(colIndex);
}
 
Example 15
Project: calcite-avatica   File: JdbcResultSet.java   View Source Code Vote up 4 votes
private static Object getValue(ResultSet resultSet, int type, int j,
    Calendar calendar) throws SQLException {
  switch (type) {
  case Types.BIGINT:
    final long aLong = resultSet.getLong(j + 1);
    return aLong == 0 && resultSet.wasNull() ? null : aLong;
  case Types.INTEGER:
    final int anInt = resultSet.getInt(j + 1);
    return anInt == 0 && resultSet.wasNull() ? null : anInt;
  case Types.SMALLINT:
    final short aShort = resultSet.getShort(j + 1);
    return aShort == 0 && resultSet.wasNull() ? null : aShort;
  case Types.TINYINT:
    final byte aByte = resultSet.getByte(j + 1);
    return aByte == 0 && resultSet.wasNull() ? null : aByte;
  case Types.DOUBLE:
  case Types.FLOAT:
    final double aDouble = resultSet.getDouble(j + 1);
    return aDouble == 0D && resultSet.wasNull() ? null : aDouble;
  case Types.REAL:
    final float aFloat = resultSet.getFloat(j + 1);
    return aFloat == 0D && resultSet.wasNull() ? null : aFloat;
  case Types.DATE:
    final Date aDate = resultSet.getDate(j + 1, calendar);
    return aDate == null
        ? null
        : (int) (aDate.getTime() / DateTimeUtils.MILLIS_PER_DAY);
  case Types.TIME:
    final Time aTime = resultSet.getTime(j + 1, calendar);
    return aTime == null
        ? null
        : (int) (aTime.getTime() % DateTimeUtils.MILLIS_PER_DAY);
  case Types.TIMESTAMP:
    final Timestamp aTimestamp = resultSet.getTimestamp(j + 1, calendar);
    return aTimestamp == null ? null : aTimestamp.getTime();
  case Types.ARRAY:
    final Array array = resultSet.getArray(j + 1);
    if (null == array) {
      return null;
    }
    try {
      // Recursively extracts an Array using its ResultSet-representation
      return extractUsingResultSet(array, calendar);
    } catch (UnsupportedOperationException | SQLFeatureNotSupportedException e) {
      // Not every database might implement Array.getResultSet(). This call
      // assumes a non-nested array (depends on the db if that's a valid assumption)
      return extractUsingArray(array, calendar);
    }
  case Types.STRUCT:
    Struct struct = resultSet.getObject(j + 1, Struct.class);
    Object[] attrs = struct.getAttributes();
    List<Object> list = new ArrayList<>(attrs.length);
    for (Object o : attrs) {
      list.add(o);
    }
    return list;
  default:
    return resultSet.getObject(j + 1);
  }
}
 
Example 16
Project: calcite-avatica   File: ColumnMetaData.java   View Source Code Vote up 4 votes
/** Returns the value of a column of this type from a result set. */
public Object jdbcGet(ResultSet resultSet, int i) throws SQLException {
  switch (this) {
  case PRIMITIVE_BOOLEAN:
    return resultSet.getBoolean(i);
  case PRIMITIVE_BYTE:
    return resultSet.getByte(i);
  case PRIMITIVE_SHORT:
    return resultSet.getShort(i);
  case PRIMITIVE_INT:
    return resultSet.getInt(i);
  case PRIMITIVE_LONG:
    return resultSet.getLong(i);
  case PRIMITIVE_FLOAT:
    return resultSet.getFloat(i);
  case PRIMITIVE_DOUBLE:
    return resultSet.getDouble(i);
  case BOOLEAN:
    final boolean aBoolean = resultSet.getBoolean(i);
    return resultSet.wasNull() ? null : aBoolean;
  case BYTE:
    final byte aByte = resultSet.getByte(i);
    return resultSet.wasNull() ? null : aByte;
  case SHORT:
    final short aShort = resultSet.getShort(i);
    return resultSet.wasNull() ? null : aShort;
  case INTEGER:
    final int anInt = resultSet.getInt(i);
    return resultSet.wasNull() ? null : anInt;
  case LONG:
    final long aLong = resultSet.getLong(i);
    return resultSet.wasNull() ? null : aLong;
  case FLOAT:
    final float aFloat = resultSet.getFloat(i);
    return resultSet.wasNull() ? null : aFloat;
  case DOUBLE:
    final double aDouble = resultSet.getDouble(i);
    return resultSet.wasNull() ? null : aDouble;
  case JAVA_SQL_DATE:
    return resultSet.getDate(i);
  case JAVA_SQL_TIME:
    return resultSet.getTime(i);
  case JAVA_SQL_TIMESTAMP:
    return resultSet.getTimestamp(i);
  case ARRAY:
    return resultSet.getArray(i);
  case STRUCT:
    return resultSet.getObject(i, Struct.class);
  default:
    return resultSet.getObject(i);
  }
}
 
Example 17
Project: blanco-sfdc-jdbc-driver   File: BlancoSfdcJdbcStatement1Test.java   View Source Code Vote up 4 votes
public void test001() throws Exception {
	if (BlancoSfdcJdbcTestConstants.isTestWithSfdc() == false)
		return;

	Class.forName("blanco.sfdc.jdbc.driver.BlancoSfdcJdbcDriver");
	try {
		final Properties prop = new Properties();
		final InputStream inStream = new FileInputStream("soqlro.properties");
		prop.load(new BufferedInputStream(inStream));
		inStream.close();

		final String url = prop.getProperty("url",
				"jdbc:blanco:sfdc:soqlro://login.salesforce.com/services/Soap/u/40.0");
		final String user = prop.getProperty("user", "NoUserSpesified");
		final String pass = prop.getProperty("password", "NoPassSpecified");

		final Connection conn = DriverManager.getConnection(url, user, pass);

		final Statement stmt = conn.createStatement();

		stmt.setFetchSize(200);
		stmt.getFetchSize();

		// final String sql = "SELECT Id, Name, LastModifiedDate FROM
		// Account";

		// final String sql = "select ApiVersion, Body, BodyCrc,
		// CreatedById, CreatedDate, Id, IsValid, LastModifiedById,
		// LastModifiedDate, LengthWithoutComments, Name, NamespacePrefix,
		// Status, SystemModstamp from ApexClass";

		final String sql = "SELECT Id, Name, LastModifiedDate FROM Contact";
		final ResultSet rs = stmt.executeQuery(sql);
		while (rs.next()) {
			final String id = rs.getString("id");
			final String name = rs.getString("name");
			final java.sql.Date lastModifiedDate = rs.getDate("LastModifiedDate");
			final java.sql.Timestamp lastModifiedDateTimestamp = rs.getTimestamp("LastModifiedDate");

			final String line = "id: " + id + ", name:" + name + ", LastModifiedDate:" + lastModifiedDate
					+ ", LastModifiedDate2:" + lastModifiedDateTimestamp;
		}
		rs.close();
		stmt.close();
		conn.close();

	} catch (SQLException ex) {
		System.out.println(ex.getMessage());
		ex.printStackTrace();
		fail();
	}
}
 
Example 18
Project: ChronoBike   File: ColValueDate.java   View Source Code Vote up 4 votes
public void doFillWithResurltSetCol(ResultSet resultSet, int nCol)
	throws SQLException
{
	m_dateValue = resultSet.getDate(nCol);
}
 
Example 19
Project: dev-courses   File: TestDatetimeSimple.java   View Source Code Vote up 4 votes
public void testValues() throws SQLException {

        TestUtil.deleteDatabase("/hsql/tests/testdatetimesimple");

        Connection conn = DriverManager.getConnection(connectionURL, "SA", "");
        ResultSet          rs;
        PreparedStatement  ps;
        String             s;
        Object             o;
        java.sql.Date      d;
        java.sql.Timestamp ts;
        Statement          st = conn.createStatement();

        st.executeUpdate("SET TIME ZONE INTERVAL '-5:00' HOUR TO MINUTE");
        st.executeUpdate("DROP TABLE t3 IF EXISTS");
        st.executeUpdate("CREATE TABLE t3(d date)");
        st.executeUpdate("INSERT INTO t3 VALUES('2008-11-27')");

        rs = st.executeQuery("SELECT d FROM t3");

        rs.next();

        s  = rs.getString("d");
        o  = rs.getObject("d");
        d  = rs.getDate("d");
        ts = rs.getTimestamp("d");

        System.out.println("2008-11-27 INSERTED" + "\n    String: " + s
                           + "\n    Object: " + o + "\n    Date: " + dump(d)
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();
        st.executeUpdate("DROP TABLE ts IF EXISTS");
        st.executeUpdate(
            "CREATE TABLE ts(id integer generated by default as identity (start with 1), ts timestamp, tsz timestamp with time zone)");
        st.executeUpdate(
            "INSERT INTO ts VALUES DEFAULT, LOCALTIMESTAMP, CURRENT_TIMESTAMP");

        rs = st.executeQuery("CALL CURRENT_DATE");

        rs.next();

        o  = rs.getObject(1);
        d  = rs.getDate(1);
        s  = rs.getString(1);
        ts = rs.getTimestamp(1);

        System.out.println("CURRENT_DATE @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Date: " + dump(d) + "\n    Timestamp: "
                           + dump(ts) + '\n');
        rs.close();

        rs = st.executeQuery("CALL LOCALTIMESTAMP");

        rs.next();

        o  = rs.getObject(1);
        s  = rs.getString(1);
        ts = rs.getTimestamp(1);

        System.out.println("LOCALTIMESTAMP @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();

        rs = st.executeQuery("CALL CURRENT_TIMESTAMP");

        rs.next();

        s  = rs.getString(1);
        o  = rs.getObject(1);
        ts = rs.getTimestamp(1);

        System.out.println("CURRENT_TIMESTAMP @" + new java.util.Date()
                           + "\n    String: " + s + "\n    Object: " + o
                           + "\n    Timestamp: " + dump(ts) + '\n');
        rs.close();
        st.executeUpdate("SHUTDOWN");
        conn.close();
    }
 
Example 20
Project: aliyun-maxcompute-data-collectors   File: JdbcWritableBridge.java   View Source Code Vote up 4 votes
public static Date readDate(int colNum, ResultSet r) throws SQLException {
  return r.getDate(colNum);
}