- Использование базовых типов данных
- Сопоставление типов данных
- Извлечение данных в виде строки
- Извлечение данных по типу данных
- Обновление данных по типу данных
- Обновление по параметризированному запросу
- Передача параметров хранимой процедуре
- Извлечение параметров из хранимой процедуры
- Sql timestamp java type
- Methods inherited from class java.util.Date
- Methods inherited from class java.lang.Object
- Constructor Detail
- Timestamp
- Timestamp
- Method Detail
- setTime
- getTime
- valueOf
- toString
- getNanos
- setNanos
- equals
- equals
- before
- after
- compareTo
- compareTo
- hashCode
- valueOf
- toLocalDateTime
- from
- toInstant
- Class Timestamp
- Class Timestamp
Использование базовых типов данных
Драйвер Microsoft JDBC Driver для SQL Server использует базовые типы данных JDBC для преобразования типов данных SQL Server в формат языка программирования Java и обратно. Драйвер JDBC обеспечивает поддержку API JDBC 4.0, в том числе типа данных SQLXML и типов данных Юникода для национальных символов: NCHAR, NVARCHAR, LONGNVARCHAR и NCLOB.
Сопоставление типов данных
В следующей таблице перечислены все сопоставления по умолчанию между базовыми типами данных SQL Server, типами данных JDBC и типами данных языка программирования Java:
1 Чтобы использовать java.sql.Time с типом времени SQL Server, нужно задать для свойства подключения sendTimeAsDatetime значение «false».
2 Значения datetimeoffset можно получить программным образом с помощью класса DateTimeOffset.
3 Обратите внимание, что значения java.sql.Timestamp больше нельзя использовать для сравнения значений из столбца datetime, начиная с SQL Server 2016. Это ограничение обусловлено изменением на стороне сервера, которое иначе преобразует datetime в datetime2, в результате чего получаются не равнозначные значения. Чтобы решить эту проблему, можно либо изменить столбцы datetime на datetime2(3), использовать строку вместо java.sql.Timestamp или изменить уровень совместимости базы данных на 120 или ниже.
В следующих разделах приводятся примеры использования драйвера JDBC и базовых типов данных. Более подробный пример использования базовых типов данных в приложении Java см. в разделе Образец базовых типов данных.
Извлечение данных в виде строки
Если вам нужно получить из источника данные, соответствующие каким-либо базовым типам данных JDBC, и просмотреть их в виде строки, или если строго типизированные данные не требуются, вы можете воспользоваться методом getString класса SQLServerResultSet, как показано далее:
try(Statement stmt = con.createStatement();)
Извлечение данных по типу данных
Если вам нужно получить из источника данные известного типа, воспользуйтесь одним из методов get класса SQLServerResultSet, также известных как методы получения. С методами get можно использовать имя столбца или его индекс:
try(Statement stmt = con.createStatement();)
Применение getUnicodeStream и getBigDecimal в сочетании с методами масштабирования считается устаревшим и не поддерживается драйвером JDBC.
Обновление данных по типу данных
Если вам нужно обновить значение поля в источнике данных, воспользуйтесь одним из методов update класса SQLServerResultSet. В следующем примере для обновления данных в источнике используется метод updateInt совместно с методом updateRow:
try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);)
Драйвер JDBC не может обновить столбец SQL Server, если имя столбца длиннее, чем 127 символов. При попытке обновить столбец, имя которого длиннее 127 символов, возникнет исключение.
Обновление по параметризированному запросу
Если вам нужно обновить данные в источнике с помощью параметризированного запроса, вы можете задать тип данных для параметров одним из методов set класса SQLServerPreparedStatement, также известных как методы задания. В следующем примере метод prepareStatement используется для предварительной компиляции параметризированного запроса, затем метод setString задает строковое значение параметра, после чего вызывается метод executeUpdate.
try(PreparedStatement pstmt = con.prepareStatement("UPDATE employee SET fname = ? WHERE (lname = 'Brown')");)
Дополнительные сведения о параметризованных запросах см. в этой статье.
Передача параметров хранимой процедуре
Если вам нужно передать параметры типа хранимой процедуре, вы можете задать параметры по имени или индексу с помощью методов set класса SQLServerCallableStatement. В следующем примере метод prepareCall используется для вызова хранимой процедуры, затем с помощью метода setString задается параметр для вызова, после чего вызывается метод executeQuery.
try(CallableStatement cstmt = con.prepareCall("");)
В данном примере возвращается результирующий набор с результатами запуска хранимой процедуры.
Дополнительные сведения об использовании драйвера JDBC с хранимыми процедурами и входными параметрами см. в этой статье.
Извлечение параметров из хранимой процедуры
Если вам нужно получить параметры обратно из хранимой процедуры, то нужно сначала зарегистрировать параметр OUT по имени или индексу при помощи метода registerOutParameter класса SQLServerCallableStatement, а затем после вызова хранимой процедуры назначить возвращаемый параметр OUT надлежащей переменной. В следующем примере сначала используется метод prepareCall для настройки вызова хранимой процедуры, затем — метод registerOutParameter для настройки параметра OUT, затем — метод setString для задания параметра вызова, после чего вызывается метод executeQuery. Значение, возвращаемое параметром OUT хранимой процедуры, извлекается с помощью метода getShort.
try(CallableStatement cstmt = con.prepareCall("");)
В дополнение к возвращаемому параметру OUT также можно вернуть результирующий набор с результатами запуска хранимой процедуры.
Дополнительные сведения об использовании драйвера JDBC с хранимыми процедурами и выходными параметрами см. в этой статье.
Sql timestamp java type
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime .
Methods inherited from class java.util.Date
Methods inherited from class java.lang.Object
Constructor Detail
Timestamp
@Deprecated public Timestamp(int year, int month, int date, int hour, int minute, int second, int nano)
Timestamp
public Timestamp(long time)
Constructs a Timestamp object using a milliseconds time value. The integral seconds are stored in the underlying date value; the fractional seconds are stored in the nanos field of the Timestamp object.
Method Detail
setTime
public void setTime(long time)
Sets this Timestamp object to represent a point in time that is time milliseconds after January 1, 1970 00:00:00 GMT.
getTime
Returns the number of milliseconds since January 1, 1970, 00:00:00 GMT represented by this Timestamp object.
valueOf
toString
Formats a timestamp in JDBC timestamp escape format. yyyy-mm-dd hh:mm:ss.fffffffff , where ffffffffff indicates nanoseconds.
getNanos
setNanos
public void setNanos(int n)
equals
equals
Tests to see if this Timestamp object is equal to the given object. This version of the method equals has been added to fix the incorrect signature of Timestamp.equals(Timestamp) and to preserve backward compatibility with existing class files. Note: This method is not symmetric with respect to the equals(Object) method in the base class.
before
after
compareTo
compareTo
hashCode
Returns a hash code value for this object. The result is the exclusive OR of the two halves of the primitive long value returned by the Date.getTime() method. That is, the hash code is the value of the expression:
(int)(this.getTime()^(this.getTime() >>> 32))
The hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
valueOf
public static Timestamp valueOf(LocalDateTime dateTime)
Obtains an instance of Timestamp from a LocalDateTime object, with the same year, month, day of month, hours, minutes, seconds and nanos date-time value as the provided LocalDateTime . The provided LocalDateTime is interpreted as the local date-time in the local time zone.
toLocalDateTime
Converts this Timestamp object to a LocalDateTime . The conversion creates a LocalDateTime that represents the same year, month, day of month, hours, minutes, seconds and nanos date-time value as this Timestamp in the local time zone.
from
Obtains an instance of Timestamp from an Instant object. Instant can store points on the time-line further in the future and further in the past than Date . In this scenario, this method will throw an exception.
toInstant
Converts this Timestamp object to an Instant . The conversion creates an Instant that represents the same point on the time-line as this Timestamp .
Submit a bug or feature
For further API reference and developer documentation, see Java SE Documentation. That documentation contains more detailed, developer-targeted descriptions, with conceptual overviews, definitions of terms, workarounds, and working code examples.
Copyright © 1993, 2023, Oracle and/or its affiliates. All rights reserved. Use is subject to license terms. Also see the documentation redistribution policy.
Class Timestamp
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.
- 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss
- 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.[fff. ] and s represents the scale of the given Timestamp, its fractional seconds precision.
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds — the nanos — are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn’t an instance of java.sql.Timestamp , because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date . The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.
Class Timestamp
A thin wrapper around java.util.Date that allows the JDBC API to identify this as an SQL TIMESTAMP value. It adds the ability to hold the SQL TIMESTAMP fractional seconds value, by allowing the specification of fractional seconds to a precision of nanoseconds. A Timestamp also provides formatting and parsing operations to support the JDBC escape syntax for timestamp values.
- 19 , which is the number of characters in yyyy-mm-dd hh:mm:ss
- 20 + s , which is the number of characters in the yyyy-mm-dd hh:mm:ss.[fff. ] and s represents the scale of the given Timestamp, its fractional seconds precision.
Note: This type is a composite of a java.util.Date and a separate nanoseconds value. Only integral seconds are stored in the java.util.Date component. The fractional seconds — the nanos — are separate. The Timestamp.equals(Object) method never returns true when passed an object that isn’t an instance of java.sql.Timestamp , because the nanos component of a date is unknown. As a result, the Timestamp.equals(Object) method is not symmetric with respect to the java.util.Date.equals(Object) method. Also, the hashCode method uses the underlying java.util.Date implementation and therefore does not include nanos in its computation.
Due to the differences between the Timestamp class and the java.util.Date class mentioned above, it is recommended that code not view Timestamp values generically as an instance of java.util.Date . The inheritance relationship between Timestamp and java.util.Date really denotes implementation inheritance, and not type inheritance.