Sobes.tech
Junior

List the main data types used in JDBC and explain how they relate to data types in Java.

sobes.tech AI

Answer from AI

The main JDBC data types are defined in the java.sql.Types class. They represent standard SQL types. JVM data types in Java are defined in the language specification. JDBC provides a mapping between these two sets of types.

Main types in java.sql.Types:

  • BOOLEAN
  • TINYINT
  • SMALLINT
  • INTEGER
  • BIGINT
  • REAL
  • FLOAT
  • DOUBLE
  • DECIMAL
  • NUMERIC
  • CHAR
  • VARCHAR
  • LONGVARCHAR
  • DATE
  • TIME
  • TIMESTAMP
  • BINARY
  • VARBINARY
  • LONGVARBINARY
  • BLOB
  • CLOB
  • NCHAR
  • NVARCHAR
  • LONGNVARCHAR
  • NCLOB
  • SQLXML

Mapping between JDBC types and Java types when retrieving data (from ResultSet):

JDBC Type Java Type (get) Notes
BOOLEAN, BIT boolean
TINYINT byte
SMALLINT short
INTEGER int
BIGINT long
REAL float
FLOAT, DOUBLE double
DECIMAL, NUMERIC java.math.BigDecimal Recommended
CHAR, VARCHAR, LONGVARCHAR String
DATE java.sql.Date
TIME java.sql.Time
TIMESTAMP java.sql.Timestamp
BINARY, VARBINARY, LONGVARBINARY byte[]
BLOB java.sql.Blob
CLOB java.sql.Clob
NCHAR, NVARCHAR, LONGNVARCHAR String
NCLOB java.sql.NClob
SQLXML java.sql.SQLXML

Note: For numeric types, besides primitive types, you can use corresponding wrapper classes (Boolean, Byte, Short, Integer, Long, Float, Double) to handle NULL values.

When setting data (in PreparedStatement), the typical mapping is reversed, but there are exceptions and preferences. For example, for DECIMAL, it is better to use BigDecimal.

Example usage:

// Method to get data from ResultSet
public String getStringValue(ResultSet rs, String columnName) throws SQLException {
    // Get string value from column
    return rs.getString(columnName);
}

// Method to set parameter in PreparedStatement
public void setIntValue(PreparedStatement ps, int parameterIndex, int value) throws SQLException {
    // Set integer value in query parameter
    ps.setInt(parameterIndex, value);
}
List the main data types used in JDBC and explain how… - sobes.tech