来自ResultSet java的getDateTime
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了来自ResultSet java的getDateTime相关的知识,希望对你有一定的参考价值。
使用getDate()
仅返回一个Date
,因此,在您的情况下,如果您想同时使用日期和时间,请使用getTimestamp(String columnLabel)
-应该可以,也可以用数据库中的实际列名替换String columnLabel
。
或使用从日期到字符串的类型转换:
resultSet.getDate(1).toString());
将返回:
2014-02-18
数据库字段数据:“ 2014-02-18 00:00:00.000”
将
java.sql.Timestamp
转换为java.util.Date
。
java.util.Date date = rs.getDate(index_position); // O/P: DD:MM:YYYY
java.sql.Timestamp timestamp = rs.getTimestamp(index_position); // O/P: DD:MM:YYYY HH:mm:ss
java.util.Date date = new java.util.Date(timestamp.getTime());
如果将时间戳记为日期并将其转换为java.sql.Timestamp
,则结果将显示为DD:MM:YYYY 00:00:00
,因为日期将无法覆盖时间。因此,它选择默认值为00:00:00
。
SQL TimeStamp : 30.12.2020 13.40.50
Java TimeStamp : 30.12.2020 13.40.50
SQL TimeStamp : 30.12.2020 13.40.50
Java Date : 30.12.2020 00.00.00
Java TimeStamp : 30.12.2020 00.00.00
获取基于ResultSetMetaData
的CSV报告的记录的示例:
ResultSetMetaData
public static void getTestTable(Connection con) throws SQLException {
String sql = "select ID, INSERTDATE, TO_CHAR(INSERTTIME,'DD.MM.YYYY HH24:MI:SS') as String_Time, INSERTTIME, MSG from TEST_TABLE group by ID, INSERTDATE, INSERTTIME, MSG";
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery(sql);
if (rs != null) {
ResultSetMetaData resultSetMetaData = rs.getMetaData();
int noOfColumns = resultSetMetaData.getColumnCount(); // For iteration
System.out.println("No of Cloumns Query Returns: "+ noOfColumns);
HashMap<String, ArrayList<?>> matrixTable = getMatrixMetadata(resultSetMetaData);
System.out.println("MatrixTable: "+matrixTable);
ArrayList<String> dataTypeList = (ArrayList<String>) matrixTable.get("ColumnTypeName");
int rowCount = 0;
while (rs.next()) { // CSV Report
for (int columnIndex = 1; columnIndex <= noOfColumns; columnIndex++) {
// int id = rs.getInt("ID");
String value = getMatrixValue(rs, dataTypeList, columnIndex);
System.out.print(value);
if (columnIndex < noOfColumns) {
System.out.print(",");
}
}
System.out.println();
rowCount++;
}
System.out.println("Result FetchSize(Total Coloumns):"+rs.getFetchSize()+" = Rows*Coloums:["+rowCount+"*"+noOfColumns+"]");
}
}
static HashMap<String, ArrayList<?>> getMatrixMetadata(ResultSetMetaData meta) throws SQLException {
int columnsCount = meta.getColumnCount();
ArrayList<String> columnList = new ArrayList<String>();
ArrayList<String> dataTypeNameList = new ArrayList<String>();
ArrayList<Integer> dataTypeIdList = new ArrayList<Integer>();
HashMap<String, ArrayList<?>> returnHashMap = new HashMap<String, ArrayList<?>>();
for (int i = 1; i <= columnsCount; i++) {
columnList.add(meta.getColumnName(i));
dataTypeIdList.add(Integer.valueOf(meta.getColumnType(i)));
dataTypeNameList.add(meta.getColumnTypeName(i));
}
returnHashMap.put("ColumnName", columnList);
returnHashMap.put("ColumnTypeId", dataTypeIdList);
returnHashMap.put("ColumnTypeName", dataTypeNameList);
return returnHashMap;
}
static DecimalFormat DECIMAL_FORMAT = (DecimalFormat) NumberFormat.getInstance(Locale.ENGLISH);
static { // https://docs.oracle.com/javase/7/docs/api/java/text/DecimalFormat.html
DECIMAL_FORMAT.applyPattern("######.###"); // "#,#00.0#" → 1,234.56
}
public static String getMatrixValue(ResultSet rs, ArrayList<String> dataTypeNameList, int pos) throws SQLException {
String retval;
String columnTypeName = dataTypeNameList.get(pos - 1);
//int type = dataTypeIdList.get(pos - 1);
//if (type == Types.DECIMAL || type == Types.DOUBLE || type == Types.FLOAT || type == Types.NUMERIC || type == Types.REAL) {
if (columnTypeName.equalsIgnoreCase("NUMBER")) {
double doubleValue = rs.getDouble(pos);
if (rs.wasNull()) {
retval = null;
} else {
retval = "[N]"+DECIMAL_FORMAT.format(doubleValue);
}
} else if (columnTypeName.equalsIgnoreCase("DATE")) {
java.util.Date date = rs.getDate(pos);
if (rs.wasNull()) { // Checks last column read had a value of SQL NULL.
retval = null;
} else {
retval = "[D]"+formatDate(date, "dd.MM.yy");
}
} else if (columnTypeName.equalsIgnoreCase("TIMESTAMP")) {
java.sql.Timestamp timestamp = rs.getTimestamp(pos);
if (rs.wasNull()) {
retval = null;
} else {
java.util.Date date = new java.util.Date(timestamp.getTime());
retval = "[T]"+formatDate(date, "dd.MM.yyyy HH:mm");
}
} else { // VARCHAR2
retval = "[S]"+rs.getString(pos);
}
return retval;
}
public static String formatDate(Date aDate, String formatStr) {
DateFormat dateFormat = new SimpleDateFormat( formatStr );
//dateFormat.setCalendar(Calendar.getInstance(TimeZone.getTimeZone("IST")));
return dateFormat.format(aDate);
}
涉及的SQL查询用于表创建和多记录插入:No of Cloumns Query Returns: 5
MatrixTable: {ColumnName=[ID, INSERTDATE, STRING_TIME, INSERTTIME, MSG], ColumnTypeId=[2, 93, 12, 93, 12], ColumnTypeName=[NUMBER, DATE, VARCHAR2, TIMESTAMP, VARCHAR2]}
[N]1,[D]30.12.20,[S]30.12.2020 00:40:50,[T]30.12.2020 00:40,[S]Insert1
[N]2,[D]30.12.20,[S]30.12.2020 13:40:50,[T]30.12.2020 13:40,[S]Insert2
Result FetchSize(Total Coloumns):10 = Rows*Coloums:[2*5]
Oracle Multi insert
在MySQL中,首选时间戳优先于日期时间
[首先,如果数据库中的日期时间表示一个时间点,请为此使用MySQL中的CREATE TABLE SCHEMA7.TEST_TABLE ( "ID" NUMBER, "INSERTDATE" DATE, "INSERTTIME" TIMESTAMP (6), "MSG" VARCHAR2(120 BYTE) );
INSERT INTO SCHEMA7.TEST_TABLE (ID, INSERTDATE, INSERTTIME, MSG) VALUES ('1', TO_DATE('30-DEC-2020', 'DD-MON-RR'), TO_TIMESTAMP('30-DEC-2020 12.40.50.00 AM', 'DD-MON-RR HH.MI.SS.FF AM'), 'Insert1');
INSERT INTO SCHEMA7.TEST_TABLE (ID, INSERTDATE, INSERTTIME, MSG) VALUES ('2', TO_DATE('30.12.2020', 'DD.MM.YYYY'), TO_TIMESTAMP('30.12.2020 13.40.50','dd.mm.yyyy hh24.mi.ss'), 'Insert2');
数据类型,而不是timestamp
。 datetime
打开以解释阅读器或正巧使用它的程序的任何时区。这可能会导致难以调试的错误。 datetime
数据类型在各种RDBMS中的行为不同。在MySQL中,它确保日期和时间使用UTC,从而将错误的解释排除在任何其他时区之外。更安全。如果您所在时区的用户更难以读取日期和时间,则值得。
java.time
timestamp
使用 PreparedStatement ps = yourDatabaseConnection.prepareStatement("select your_datetime_col from your_table;");
try (ResultSet rs = ps.executeQuery()) {
while (rs.next()) {
OffsetDateTime dateTime = rs.getObject("your_datetime_col", OffsetDateTime.class);
// do something with dateTime
}
}
从数据库将日期和时间检索为现代Java日期和时间API java.time的类型。问题中提到或暗示的ResultSet.getObject()
,java.sql.Timestamp
和java.sql.Date
类以及
以上是关于来自ResultSet java的getDateTime的主要内容,如果未能解决你的问题,请参考以下文章
Mysql Java Derby Netbeans:不允许“deleteRow”,因为 ResultSet 不是可更新的 ResultSet