O'Reilly logo

Ivor Horton's Beginning Java™ 2, JDK™ 5th Edition by Ivor Horton

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

25.1. Data Types and JDBC

In all of the examples so far, all of the data extracted from a resultset was retrieved as a String. You'll certainly need to get other types of data, and as you saw in the previous chapter, the ResultSet provides a number of methods for retrieving different data types. To use these effectively, you need to look at the SQL data types and understand how they map to the Java data types in your program.

25.1.1. Mapping between Java and SQL Data Types

The SQL-92 standard defines a set of data types that don't map one-for-one with those in Java. As you write applications that move data from SQL to Java and back, you'll have to take account of how JDBC performs that mapping. That is, you need to know the Java data type you need to represent a given SQL data type, and vice versa.

The Types class in the java.sql package defines constants of type int that represent each of the supported SQL types. The name given to the data member storing each constant is the same as that of the corresponding SQL type. For example, when you retrieve the SQL type of a table column by calling the getColumnType() method for a ResultSetMetaData object, the SQL type is returned as one of the constants defined in the Types class.

When you're retrieving data from a JDBC data source, the ResultSet implementation will map the SQL data onto Java data types. The following table shows the SQL-to-Java mappings:

SQL Data TypeJava Data Type
CHARString
VARCHARString
LONGVARCHARString
NUMERICjava.math.BigDecimal ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required