sql server java类型_使用基本 JDBC 数据类型 - SQL Server | Microsoft Docs

使用基本数据类型Using basic data types

01/29/2021

本文内容

Microsoft JDBC Driver for SQL ServerMicrosoft JDBC Driver for SQL Server 使用 JDBC 基本数据类型将 SQL ServerSQL Server 数据类型转换为 Java 编程语言能够理解的格式,反之亦然。The Microsoft JDBC Driver for SQL ServerMicrosoft JDBC Driver for SQL Server uses the JDBC basic data types to convert the SQL ServerSQL Server data types to a format that can be understood by the Java programming language, and vice versa. JDBC 驱动程序支持 JDBC 4.0 API,其中包括 SQLXML 数据类型和区域 (Unicode) 数据类型,如 NCHAR 、NVARCHAR 、LONGNVARCHAR 和 NCLOB 。The JDBC driver provides support for the JDBC 4.0 API, which includes the SQLXML data type, and National (Unicode) data types, such as NCHAR, NVARCHAR, LONGNVARCHAR, and NCLOB.

数据类型映射Data type mappings

下表列出了基本 SQL ServerSQL Server、JDBC 和 Java 编程语言数据类型之间的默认映射:The following table lists the default mappings between the basic SQL ServerSQL Server, JDBC, and Java programming language data types:

SQL Server 类型SQL Server Types

JDBC 类型 (java.sql.Types)JDBC Types (java.sql.Types)

Java 语言类型Java Language Types

bigintbigint

BIGINTBIGINT

longlong

binarybinary

BINARYBINARY

byte[]byte[]

bitbit

BITBIT

booleanboolean

charchar

CHARCHAR

字符串String

datedate

DATEDATE

java.sql.Datejava.sql.Date

datetime3datetime3

TIMESTAMPTIMESTAMP

java.sql.Timestampjava.sql.Timestamp

datetime2datetime2

TIMESTAMPTIMESTAMP

java.sql.Timestampjava.sql.Timestamp

datetimeoffset2datetimeoffset2

microsoft.sql.Types.DATETIMEOFFSETmicrosoft.sql.Types.DATETIMEOFFSET

microsoft.sql.DateTimeOffsetmicrosoft.sql.DateTimeOffset

Decimaldecimal

DECIMALDECIMAL

java.math.BigDecimaljava.math.BigDecimal

FLOATfloat

DOUBLEDOUBLE

doubledouble

imageimage

LONGVARBINARYLONGVARBINARY

byte[]byte[]

intint

INTEGERINTEGER

intint

moneymoney

DECIMALDECIMAL

java.math.BigDecimaljava.math.BigDecimal

ncharnchar

CHARCHAR

NCHAR (Java SE 6.0)NCHAR (Java SE 6.0)

字符串String

ntextntext

LONGVARCHARLONGVARCHAR

LONGNVARCHAR (Java SE 6.0)LONGNVARCHAR (Java SE 6.0)

字符串String

numericnumeric

NUMERICNUMERIC

java.math.BigDecimaljava.math.BigDecimal

nvarcharnvarchar

VARCHARVARCHAR

NVARCHAR (Java SE 6.0)NVARCHAR (Java SE 6.0)

字符串String

nvarchar(max)nvarchar(max)

VARCHARVARCHAR

NVARCHAR (Java SE 6.0)NVARCHAR (Java SE 6.0)

字符串String

realreal

realREAL

FLOATfloat

smalldatetimesmalldatetime

TIMESTAMPTIMESTAMP

java.sql.Timestampjava.sql.Timestamp

smallintsmallint

SMALLINTSMALLINT

shortshort

smallmoneysmallmoney

DECIMALDECIMAL

java.math.BigDecimaljava.math.BigDecimal

texttext

LONGVARCHARLONGVARCHAR

字符串String

timetime

TIME1TIME1

java.sql.Time1java.sql.Time1

timestamptimestamp

BINARYBINARY

byte[]byte[]

tinyinttinyint

TINYINTTINYINT

shortshort

udtudt

VARBINARYVARBINARY

byte[]byte[]

uniqueidentifieruniqueidentifier

CHARCHAR

字符串String

varbinaryvarbinary

VARBINARYVARBINARY

byte[]byte[]

varbinary(max)varbinary(max)

VARBINARYVARBINARY

byte[]byte[]

varcharvarchar

VARCHARVARCHAR

字符串String

varchar(max)varchar(max)

VARCHARVARCHAR

字符串String

xmlxml

LONGVARCHARLONGVARCHAR

LONGNVARCHAR (Java SE 6.0)LONGNVARCHAR (Java SE 6.0)

字符串String

SQLXMLSQLXML

sqlvariantsqlvariant

microsoft.sql.Types.SQL_VARIANTmicrosoft.sql.Types.SQL_VARIANT

对象Object

geometrygeometry

VARBINARYVARBINARY

byte[]byte[]

geographygeography

VARBINARYVARBINARY

byte[]byte[]

1 若要将 java.sql.Time 与时间 SQL ServerSQL Server 类型一起使用,必须将 sendTimeAsDatetime 连接属性设置为 false。1 To use java.sql.Time with the time SQL ServerSQL Server type, you must set the sendTimeAsDatetime connection property to false.

2 可以编程方式使用 DateTimeOffset 类访问 datetimeoffset 的值。2 You can programmatically access values of datetimeoffset with DateTimeOffset Class.

3 请注意,从 SQL Server 2016 开始,java.sql.Timestamp 值不能再用于比较 datetime 列中的值。3 Note that java.sql.Timestamp values can no longer be used to compare values from a datetime column starting from SQL Server 2016. 此限制是由于以不同方式将 datetime 转换为 datetime2 的服务器端更改,从而导致不可相等的值。This limitation is due to a server-side change that converts datetime to datetime2 differently, resulting in non-equitable values. 此问题的解决方法是将 datetime 列更改为 datetime2(3),使用 String 而不是 java.sql.Timestamp,或将数据库兼容级别更改为 120 或更低。The workaround to this issue is to either change datetime columns to datetime2(3), use String instead of java.sql.Timestamp, or change database compatibility level to 120 or below.

以下几部分提供了如何使用 JDBC 驱动程序和基本数据类型的示例。The following sections provide examples of how you can use the JDBC Driver and the basic data types. 有关如何在 Java 应用程序中使用基本数据类型的更多详细示例,请参阅基本数据类型示例。For a more detailed example of how to use the basic data types in a Java application, see Basic Data Types Sample.

以字符串格式检索数据Retrieving data as a string

如果必须从映射到任意 JDBC 基本数据类型的数据源检索数据,并以字符串的格式查看这些数据,或者如果不需要强类型的数据,则可以使用 SQLServerResultSet 类的 getString 方法,如下所示:If you have to retrieve data from a data source that maps to any of the JDBC basic data types for viewing as a string, or if strongly typed data is not required, you can use the getString method of the SQLServerResultSet class, as in the following:

try(Statement stmt = con.createStatement();) {

ResultSet rs = stmt.executeQuery("SELECT lname, job_id FROM employee WHERE (lname = 'Brown')");

rs.next();

short empJobID = rs.getShort("job_id");

}

按数据类型检索数据Retrieving data by data type

如果必须从数据源检索数据,并且已知检索的数据类型,则应使用 SQLServerResultSet 类的任一 get 方法(也称为 Getter 方法)。If you have to retrieve data from a data source, and you know the type of data that is being retrieved, use one of the get methods of the SQLServerResultSet class, also known as the getter methods. 通过 get 方法,可以使用列名或列索引,如下所示:You can use either a column name or a column index with the get methods, as in the following:

try(Statement stmt = con.createStatement();) {

ResultSet rs = stmt.executeQuery("SELECT lname, job_id FROM employee WHERE (lname = 'Brown')");

rs.next();

short empJobID = rs.getShort("job_id");

}

备注

使用确定位数的 getUnicodeStream 和 getBigDecimal 方法已遭弃用,不受 JDBC 驱动程序支持。The getUnicodeStream and getBigDecimal with scale methods are deprecated and are not supported by the JDBC driver.

按数据类型更新数据Updating data by data type

如果必须更新数据源中字段的值,请使用 SQLServerResultSet 类的一种 update 方法。If you have to update the value of a field in a data source, use one of the update methods of the SQLServerResultSet class. 在下面的示例中,updateInt 方法与 updateRow 方法结合使用,用于更新数据源中的数据:In the following example, the updateInt method is used in conjunction with the updateRow method to update the data in the data source:

try (Statement stmt = con.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_UPDATABLE);) {

ResultSet rs = stmt.executeQuery("SELECT lname, job_id FROM employee WHERE (lname = 'Brown')");

rs.next();

int empJobID = rs.getInt(2);

empJobID++;

rs.first();

rs.updateInt(2, empJobID);

rs.updateRow();

}

备注

JDBC Driver 无法更新列名长度超过 127 个字符的 SQL Server 列。The JDBC driver cannot update a SQL Server column with a column name that is more than 127 characters long. 如果尝试更新名称长度超过 127 个字符的列,将引发异常。If an update to a column whose name is more than 127 characters is attempted, an exception is thrown.

通过参数化查询来更新数据Updating data by parameterized query

如果必须通过使用参数化查询来更新数据源中的数据,可以使用 SQLServerPreparedStatement 类的任一 set 方法(也称为 setter 方法)来设置参数的数据类型。If you have to update data in a data source by using a parameterized query, you can set the data type of the parameters by using one of the set methods of the SQLServerPreparedStatement class, also known as the setter methods. 在下面的示例中,prepareStatement 方法用于预编译参数化查询,然后在调用 executeUpdate 方法前,使用 setString 方法来设置参数的字符串值。In the following example, the prepareStatement method is used to pre-compile the parameterized query, and then the setString method is used to set the string value of the parameter before the executeUpdate method is called.

try(PreparedStatement pstmt = con.prepareStatement("UPDATE employee SET fname = ? WHERE (lname = 'Brown')");) {

String name = "Bob";

pstmt.setString(1, name);

int rowCount = pstmt.executeUpdate();

}

若要详细了解参数化查询,请参阅使用包含参数的 SQL 语句。For more information about parameterized queries, see Using an SQL statement with parameters.

向存储过程传递参数Passing parameters to a stored procedure

如果必须向存储过程传递类型参数,则可使用 SQLServerCallableStatement 类的任一 set 方法通过索引或名称来设置此参数。If you have to pass typed parameters into a stored procedure, you can set the parameters by index or name by using one of the set methods of the SQLServerCallableStatement class. 在下面的示例中,prepareCall 方法用于设置对存储过程的调用,然后在调用 executeQuery 方法之前,使用 setString 方法设置调用的参数。In the following example, the prepareCall method is used to set up the call to the stored procedure, and then the setString method is used to set the parameter for the call before the executeQuery method is called.

try(CallableStatement cstmt = con.prepareCall("{call employee_jobid(?)}");) {

String lname = "Brown";

cstmt.setString(1, lname);

ResultSet rs = cstmt.executeQuery();

}

备注

在此实例中,将返回一个结果集,包含此存储过程的运行结果。In this example, a result set is returned with the results of running the stored procedure.

若要详细了解结合使用 JDBC 驱动程序与存储过程和输入参数,请参阅使用包含输入参数的存储过程。For more information about using the JDBC driver with stored procedures and input parameters, see Using a stored procedure with input parameters.

从存储过程检索参数Retrieving parameters from a stored procedure

如果必须从存储过程检索参数,则必须首先使用 SQLServerCallableStatement 类的 registerOutParameter 方法通过名称或索引注册一个输出参数,然后在调用存储过程后,将返回的输出参数分配给合适的变量。If you have to retrieve parameters back from a stored procedure, you must first register an out parameter by name or index by using the registerOutParameter method of the SQLServerCallableStatement class, and then assign the returned out parameter to an appropriate variable after you run the call to the stored procedure. 在下面的示例中,使用 prepareCall 方法设置对存储过程的调用,使用 registerOutParameter 方法设置输出参数,然后在调用 executeQuery 方法前,使用 setString 方法设置调用的参数。In the following example, the prepareCall method is used to set up the call to the stored procedure, the registerOutParameter method is used to set up the out parameter, and then the setString method is used to set the parameter for the call before executeQuery method is called. 使用 getShort 方法来检索存储过程的输出参数返回的值。The value that is returned by the out parameter of the stored procedure is retrieved by using the getShort method.

try(CallableStatement cstmt = con.prepareCall("{call employee_jobid (?, ?)}");) {

cstmt.registerOutParameter(2, java.sql.Types.SMALLINT);

String lname = "Brown";

cstmt.setString(1, lname);

ResultSet rs = cstmt.executeQuery();

short empJobID = cstmt.getShort(2);

}

备注

除返回的输出参数外,还可能返回一个结果集,包含此存储过程的运行结果。In addition to the returned out parameter, a result set might also be returned with the results of running the stored procedure.

若要详细了解结合使用 JDBC 驱动程序与存储过程和输出参数,请参阅使用包含输出参数的存储过程。For more information about how to use the JDBC driver with stored procedures and output parameters, see Using a stored procedure with output parameters.

另请参阅See also

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值