【发布时间】:2014-11-14 12:19:43
【问题描述】:
我得到以下输出
INSERT INTO AIRPORTS VALUES(null, #{iata} , #{latitude} , #{longitude}, #{name}, #{city})airportsScript.rb:27:in `query': You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near '' at line 1 (Mysql2::Error)
from airportsScript.rb:27:in `block in getAirports'
from airportsScript.rb:20:in `each'
from airportsScript.rb:20:in `getAirports'
from airportsScript.rb:32:in `<main>'
来自这个脚本(实际上是完整的脚本):
#!/usr/bin/env ruby
require 'rubygems'
require 'json'
require 'rest-client'
require 'uri'
require 'mysql2'
def getAirports()
client = Mysql2::Client.new(:host => "localhost", :username => "****", :password => "****" , :database => "****")
url='https://api.flightstats.com/flex/airports/rest/v1/json/all?appId=APPIDHIDENKey=KEYHIDDEN'
airportsJson = JSON.parse(RestClient.get(url))
for airports in airportsJson["airports"]
iata = airports["iata"]
latitude = airports["latitude"]
longitude = airports["longitude"]
name = airports["name"]
city = airports["city"]
print 'INSERT INTO AIRPORTS VALUES(null, #{iata} , #{latitude} , #{longitude}, #{name}, #{city})'
client.query('INSERT INTO AIRPORTS VALUES(null, #{iata} , #{latitude} , #{longitude}, #{name}, #{city})')
end
client.close
end
getAirports()
您可能会注意到,在输出中,第一行来自 print 'INSERT INTO AIRPORTS VALUES(null, #{iata} , #{latitude} , #{longitude}, #{name}, #{city})' 为什么我不能得到 iata、纬度、经度等变量的值,而不是实际的字符串“#{iata}”
我是 ruby 新手,顺便说一句,这是我的第一个脚本。
【问题讨论】:
-
我不知道你在用这个脚本做什么,但是构建这样的 SQL 查询是非常不安全的。容易出现 SQL 注入等问题。
-
我只会用大量航班数据填充数据库一次。
-
一次也没关系。您应该正确引用和转义您的字符串。或者更好的是,mysql2 不可能完全损坏和无用,以至于不支持查询中的某种占位符,请使用它们。
-
我会做研究的,谢谢
-
显然是that useless,似乎根本没有任何占位符支持。哇。至少有一个
escape方法。
标签: sql ruby json string mysql2