使用基本数据类型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

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

  1. sql转java对象_关于hibernate中使用sql语句时,类对象的转换问题。

    该楼层疑似违规已被系统折叠 隐藏此楼查看此楼 @SuppressWarnings("unchecked") public List getAllStorytell(Long use ...

  2. java jdbc脚本_关于java:使用MySQL和JDBC运行.sql脚本

    我开始使用MySQL和JDBC. Class.forName("com.mysql.jdbc.Driver"); conn = DriverManager.getConnectio ...

  3. 双表查询java代码_什么是JDBC?Java数据库连接性简介

    JDBC(Java数据库连接性)是Java API,用于管理与数据库的连接,发出查询和命令以及处理从数据库获得的结果集.JDBC在1997年作为JDK 1.1的一部分发布,是为Java持久层开发的首批 ...

  4. resultset java 类型_关于JAVA中Resultset的类型

    JAVA中Resultset是一个类 而不是一个方法.记住啊. 结果集(ResultSet)是数据中查询结果返回的一种对象,可以说结果集是一个存储查询结果的对象,但是结果集并不仅仅具有存储的功能,他同 ...

  5. 怎么更改sql的实例版本_学会复杂一点的SQL语句:Oracle DDL和DML

    create:创建表创建用户创建视图 创建表 create table student(id int,score int) ; student后面与括号之间可以有空格可以没有 创建用户 create ...

  6. sql not exists用法_牛客网数据库SQL实战详细剖析(5160)(更新完结)

    文章来源:大数据肌肉猿 作者:无精疯 这是一个系列文章,总共61题,分6期,有答案以及解题思路,并附上解题的一个思考过程. 具体题目可参考牛客网的SQL实战模块: https://www.nowcod ...

  7. bigint hive java类型_三十、Hive的数据类型以及常用的属性配置

    上篇文章我们在服务器上部署了Hive并将它的Metastore存储在了MySQL上,本文介绍一下Hive的数据类型以及常用的一些属性配置.关注专栏<破茧成蝶--大数据篇>,查看更多相关的内 ...

  8. bigint hive java类型_详解Apache Hudi如何配置各种类型分区

    1. 引入 Apache Hudi支持多种分区方式数据集,如多级分区.单分区.时间日期分区.无分区数据集等,用户可根据实际需求选择合适的分区方式,下面来详细了解Hudi如何配置何种类型分区. 2. 分 ...

  9. sql date类型_共享单车数据分析的SQL数据库设计

    SQL,发音为" sequel"(或SQL,如果愿意的话),是数据科学家的重要工具.实际上,它可以说是获取数据工作中最重要的语言.在共享单车数据分析的SQL设计中,我们将从入门者的 ...

最新文章

  1. django文件上传
  2. Debian/Ubuntu 对gpg和apt-key使用代理--报错解决:gpg: keyserver receive failed: Connection timed out
  3. FLUSH TABLES WITH READ LOCK 和 LOCK TABLES
  4. mysql查询后10条数据类型_30多条mysql数据库优化方法,千万级数据库记录查询轻松解决...
  5. format函数python的顺序_[转载] Python中format函数用法
  6. javascript 查看变量类型
  7. 详解get与post请求方式、content-type与responseType、@Requestbody与@Requestparam的使用场景
  8. osg 三维gis开发_三维GIS平台的可视化应用 (下)
  9. Java多线程编程递增_java多线程编程之简介
  10. php 实现二叉树的最大深度_LeetCode题记——104二叉树的最大深度
  11. php应用处理数据 504,PHP与504服务器错误
  12. 计算机底层第一课,早学早受益
  13. 千千静听音效插件使用方法(激烈经典)
  14. java的ascii码表_ASCII码表对照
  15. linux环境变量lang=c,设置linux环境变量LANG
  16. app登录的token设计
  17. Sherlock之Instructions指令介绍(Sherlock Version: 7.2.5.1 64-bit)
  18. mysqlfrm初步使用
  19. @Resource和@Autowired的区别
  20. 激光测距DL100通讯线连接

热门文章

  1. 为什么大家都在吹捧Python?
  2. BERT or XLNet,围观NLP巅峰烧钱大战。技术发展太快,如何才能跟得上节奏?
  3. CentOS 7 从下载到安装
  4. 微服务架构与Spring Cloud Alibaba
  5. 足球 Floyd算法
  6. 语言中拟合函数 计算aic_Go语言函数深度解析(中)
  7. android二级菜单ui,Android UI 之实现多级树形列表TreeView示例
  8. 十大经典排序算法之冒泡排序及其优化
  9. java遍历文件夹并把所有文件放到list中
  10. JavaScript——易班优课YOOC课群在线测试自动答题解决方案(二十)整理维护