我收到以下输出
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,latitude,long等变量的值而不是实际的字符串&#34;#{ IATA}&#34;
我是ruby的新手,这是我的第一个脚本btw。
答案 0 :(得分:1)
使用“双引号”而不是“单引号”来插入变量。
2.0.0-p353 :001 > var = "foo"
=> "foo"
2.0.0-p353 :002 > 'Hello #{var}'
=> "Hello \#{var}"
2.0.0-p353 :003 > "Hello #{var}"
=> "Hello foo"