0

I am trying to store latitude and longitude information in MySQL. I am using Ruby to parse the latitude and longitude data. They are parsed separately and then combined into a string variable. So if I have:

latitude = 43.78219.to_s
longitude = -75.00326.to_s
location = latitude + " " + longitude  # => "43.78219 -75.00326"

I have a table in MySQL to store this data, and the data type is set to String varchar. The problem is that when I insert the location string into the table, MySQL performs a math operation and subtracts the two numbers in the string. Then I'm like Whaaaaaaaaa??????? So it ends up storing -31.22107 as the location. Am I doing something wrong?

Here is the query I'm using

db.query("insert into StationCapacityStatus
        (city_id, station_id, location, empty_docks, nonempty_docks, timestamp) 
        values(
            23,
            #{$station_number},
            #{location},
            #{$empty_docks},
            #{$nonempty_docks},
            #{$datetime}
        )"
)
5
  • Add the query you are using to save it to the database. Chances are if it isn't in quotes, then it is picking it up as an equation. Commented Mar 7, 2012 at 3:41
  • 4
    I'd store them in seperate columns anyways. Commented Mar 7, 2012 at 3:42
  • @judda Just added the query I was using. Commented Mar 7, 2012 at 3:48
  • I agree with peterbond here. It makes more logical sense to split them up. I don't know ruby enough to know the syntax on how to change your query, so I'll leave that to someone else. Commented Mar 7, 2012 at 3:49
  • I guess I'll have to go the 2 columns route to reduce the headache. Thanks. Commented Mar 7, 2012 at 3:57

1 Answer 1

2

You're not quoting the location so MySQL's sees a plain 43.78219 -75.00326 inside the VALUES and interprets it as a floating point expression. You should use quote method to properly escape the strings as well:

db.query("insert into StationCapacityStatus
    (city_id, station_id, location, empty_docks, nonempty_docks, timestamp) 
    values(
        23,
        #{$station_number},
        '#{db.quote(location)}',
        #{$empty_docks},
        #{$nonempty_docks},
        #{$datetime}
    )"
)

You should also switch to prepared statements with bound values if possible:

sth = db.prepare('insert into StationCapacityStatus (city_id, station_id, location, empty_docks, nonempty_docks, timestamp) values (?, ?, ?, ?, ?, ?)')
sth.execute(23, $station_number, location, $empty_docks, $nonempty_docks, $datetime)
Sign up to request clarification or add additional context in comments.

1 Comment

@icanc: You're welcome, separate columns (and db.prepare) is a good plan.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.