gpt4 book ai didi

MySQL 对字符串执行数学运算?

转载 作者:行者123 更新时间:2023-11-29 08:57:26 25 4
gpt4 key购买 nike

我正在尝试在 MySQL 中存储纬度和经度信息。我正在使用 Ruby 来解析纬度和经度数据。它们被单独解析,然后组合成一个字符串变量。所以如果我有:

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

我在MySQL中有一个表来存储这些数据,数据类型设置为String varchar。问题是,当我将位置字符串插入表中时,MySQL 会执行数学运算并减去字符串中的两个数字。然后我就觉得哇啊啊啊啊啊啊啊啊啊???所以它最终存储 -31.22107 作为位置。我做错了什么吗?

这是我正在使用的查询

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}
)"
)

最佳答案

您没有引用位置,因此MySQL会在VALUES中看到一个简单的43.78219 -75.00326并将其解释为浮点表达式。您应该使用 quote正确转义字符串的方法:

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}
)"
)

如果可能的话,您还应该切换到具有绑定(bind)值的准备好的语句:

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)

关于MySQL 对字符串执行数学运算?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9595462/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com