开发者

How to map standard Java types to SQL types?

I want to write a program, which creates RDBMS-tables through JDBC automatically. To add columns to a table, I need to know the name of the column and the column's RDBMS datatype. I already have the names of the columns. I don't have the RDBMS types for the columns, but I have Java types for those column. So I need to map those Java types to RDBMS datatypes. The Java type can be one of the following:

  • primitve types
  • wrapp开发者_开发百科er types of primitive types
  • String

  • So my question is: How to map those java types to RDBMS types?

  • Is there a part of JDBC or library that already handles this mapping?
  • Are there any classes which can help me partially?

Especially I am working with PostgreSQL. So if there is no genenic way to do it, it would be important for the moment to get it running with PG.

Thanks in advance


Well, there there's always the java.sql.Types class which contains the generic SQL type mappings, but you'd be better served using something like Hibernate to do all of this for you.


getTypeInfo() is intended to get the driver's view on which (native) DBMS type should be mapped to which JDBC type. But these mappings aren't always precise so you will need to find some way of detecting the "best match"


Sun/Oracle's JDBC Guide proposes some mappings:

Mapping SQL and Java Types


I don't think there is any generic way to do it. The devil is in the details : do you want to impose any precision or scale? What's the maximum number of chars in your strings?

The mapping, in its simplest form could be

Java char    --> varchar(1)
Java String  --> varchar
Java number  --> numeric
Java boolean --> boolean
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜