Tipos de Dados Postgres para Java
Tipos de Dados Postgres para Java
dados Java
https://www.instaclustr.com/blog/postgresql-data-types-mappings-to-sql-jdbc-and-java-data-types/
time [ (p) ] [ without time zone ] time of day (no time zone)
time [ (p) ] with time zone timetz time of day, including time zone
timestamp [ (p) ] [ without time zone ] date and time (no time zone)
timestamp [ (p) ] with time zone timestamptz date and time, including time zone
1
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost/?
user=name&password=abc&ssl=false");
To create tables you need to specify PostgreSQL data types for all the columns. For example, here’s a simple test table with integer
id (which is the primary key) and value columns:
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery("INSERT INTO
test1 VALUES (1,1000)");
1
2 rs = st.executeQuery("SELECT * FROM test1
4 WHERE id = 1");
3
5
while (rs.next())
System.out.print("Result = " + rs.getInt("value"));
4. Why Do Data Types Matter in JDBC?
For simple Statements, the INSERT statement is just a string, so you don’t need a real data type yet. However, to extract the returned
value you do need to know the PostgreSQL type, and also the corresponding Java data type if you are going to do anything more
useful than just print it out (i.e. store it, process it):
7 <strong>pst2.setInt(1, 2);</strong>
6
8
9
rs = pst2.executeQuery();
while (rs.next())
<strong>int value = rs.getInt("value");</strong>
Note that rs.getString(“value”) also seems to work ok for the basic data types (i.e. automatic casting), which is a feature we’ll find
useful below.
Mappings
from shape to colour
(Source: Wikimedia)
But how do you know which Java data types the PostgreSQL data types actually map to in advance?
Some searching resulted in the discovery of the getTypeInfo() method in the java.sql.DatabaseMetaData Interface, which is an
interface implemented by driver vendors to let users know the capabilities of the database in combination with the JDBC driver. The
getTypeInfo() method retrieves a description of all the data types supported by the database, ordered by DATA_TYPE and then by
how closely they map to the corresponding JDBC SQL type. There’s potentially lots of useful information available, but I was mainly
interested in TYPE_NAME and DATA_TYPE, which is the SQL data type from java.sql.Types. Initially it was reporting
DATA_TYPE as integers (corresponding to the constants in the ENUM java.sql.Types), which wasn’t very useful, but then I
managed to get it to report the constant name as follows:
rs = conn.getMetaData().getTypeInfo())
while (rs.next())
System.out.println(rs.getString("TYPE_NAME")
1
2
+ "\t" +
3
JDBCType.valueOf(rs.getInt("DATA_TYPE")).ge
tName());
Running this reveals the complete list of PostgreSQL data types and their mapping to SQL/JDBC Data types, for a total of 183 data
types. Removing all the (many) OTHER and ARRAY (e.g. _record etc) data types leaves us with this more manageable table:
bool BIT
bit BIT
int8 BIGINT
bigserial BIGINT
oid BIGINT
bytea BINARY
char CHAR
bpchar CHAR
numeric NUMERIC
int4 INTEGER
serial INTEGER
int2 SMALLINT
smallserial SMALLINT
float4 REAL
float8 DOUBLE
money DOUBLE
name VARCHAR
text VARCHAR
varchar VARCHAR
date DATE
time TIME
timetz TIME
timestamp TIMESTAMP
timestamptz TIMESTAMP
cardinal_number DISTINCT
character_data DISTINCT
sql_identifier DISTINCT
time_stamp DISTINCT
yes_or_no DISTINCT
xml SQLXML
refcursor REF_CURSOR
Table 2: Mappings From PostgreSQL to SQL/JDBC Data Types
Note that the PostgreSQL data types are using the aliases from Table 1. But this is only part of the answer. How do we know what
Java data types correspond to the SQL data types?
1 REF_CURSOR doesn’t appear in the jdbc appendices, but is mentioned in section “13.3.3.4 REF Cursor Support” of the
specification, and may map to Types.REF_CURSOR.
2 _abc stands for one of many ARRAY data types available in PostgreSQL (_record to _yes_or_no).
7. Type Conversion
So now we know the correct Java types to use, everything should just magically work correctly right? Well, mostly, as long as you
remember what the PostgreSQL data types used in the table columns are, and use the correct PostgreSQL to Java mappings. As an
experiment I tried a few data types including int2/int4/int8 (short, int, long), char/text (String), numeric (BigDecimal). The main
thing to watch out for is conversion/casting between different sized types—going from longer to short types results in run-times
errors (if you are lucky) or truncation (if you are unlucky).
How about a really simple type such as bit, bool, and boolean? That should be idiot proof? True? (or False or Unknown…). Let’s try
and see what happens (in my next PostgreSQL blog)!
8. Conclusões
In this blog I discovered what data types are available in PostgreSQL (a lot), and hopefully determined the definitive mapping from
PostgreSQL to SQL/JDBC to Java data types. However, even armed with this information you have to be careful about type
conversion/casting, and watch out for run-time errors, truncation, or loss of information.
And we’ve really only started to scratch the surface of PostgreSQL data types, as PostgreSQL allows for custom data types, user
defined types, arrays, and OTHER data types (e.g. JSON). I was also surprised to discover that PostgreSQL is really
an ORDBMS (an object-relational DB), and has support for some object-oriented features such as table inheritance and function
overloading. How these all work from JDBC would be more than enough to fill my imaginary database book, or several actual (but
currently chimerical) future blogs.