views:

1006

answers:

4

May be this question has been answered before but I couldn't find it.

I am using a 2/3 yr old MySQL database which has hyphens in its column names. When I try to use these names from my Java code, the names are broken at the hyphen (e.g. air_port becomes air) and thus are not found. I tried replacing hyphens to underscores in my code hoping that the DB might treat them equally but that doesn't work.

How can I escape the hyphen or how can I access these columns ? Could this be an issue of the character set being used ?

+4  A: 

enclose the names within `back-ticks`

dar7yl
it worked. thanx very much. SO rocks.
euphoria83
A: 

This entry at the MySQL forum suggests that you might have a problem. However, I think it's referring to data and not column names.

This says "don't do it." Don't know how authoritative it is.

duffymo
A: 

Do you have hyphens (-) or underscores (_) in your column names?

Hyphens are a big problem because if you end up mapping a column name to a variable, most languages do not like to have hyphens inside variable names. Perhaps you are using one of the Java libraries that automatically generates variables or objects whose names are based on column names.

Depending on the nature of your problem, there are a couple of different approaches you can use:

  1. Rename all of your columns using ALTER TABLE. Be conscious that this could affect referential integrity or other applications that depend on the database. If you don't know what that means, don't do it.
  2. Create SQL views that simple restate the tables you need but with "better" column names. This is not very efficient, but it will allow you to get what you want.
  3. Use the AS keyword when running your SELECT statements to rename columns within queries.

None of these are great solutions, but they should get you started. Good luck!

Robby Slaughter
A: 

is it a good practise in mysql to create a table with the name containing hyphen in it e.g. test-test2 and can the column names be made such as id-1? i tried one query on table which was containing hyphen in its name. but then it didn't worked. i removed the hyphen and then it worked.

K S
This is not a good place to ask questions. Either write a comment to an answer or ask a new question.
euphoria83