Koerr
Koerr

Reputation: 15733

possible to get mysql enum filed's index value in java?

table:

CREATE TABLE `table` (
  `id` int(11) NOT NULL,
  `status` enum('on','off') NOT NULL DEFAULT 'off',
  PRIMARY KEY (`id`),
) 

I can use the enum index value to update or insert:

update table set status=1 where id=12 (update id=2 status to on)

but in java,the Enum field type always return String (check here)

select status from table where id=2

or use resultSet.getObject("status") (java)

always return the String on, but I want to get the Integer 1

is this possible?

Upvotes: 1

Views: 1120

Answers (2)

Eugen Rieck
Eugen Rieck

Reputation: 65284

SELECT 
  CAST(`status` AS UNSIGNED) AS numerical_status
FROM `table`

Pitfall: This is 1-based, so you will get 1 for on and 2 for off

Edit

If you can't use calculated fields (for whatever reason), create a view:

CREATE OR REPLACE VIEW `table_numstatus` AS
  SELECT `id`,  CAST(`status` AS UNSIGNED) AS `status`
  FROM `table` ;

and direct your queries to this view, instead of the table.

Upvotes: 5

triclosan
triclosan

Reputation: 5714

maybe it's not what you looking for but as solution you can create Java-enum on client side and convert according to its value

Upvotes: 0

Related Questions