Storing a String saved as a Variable in a MySQL database? - mysql

In a ruby script that sends information to the TWILIO API, I have a string of characters of characters that their (Twilio's) API outputs. I then have the console output it so I can save it as a variable and reuse it later:
#client = Twilio::REST:Client.new account_sid, auth_token
call = #client.account.calls.create({:from => 'incoming', :to => 'outgoing', :url => 'url', :method => 'GET'})
puts call.sid
This part is functional, but now when I rename the variable (// #incoming_Cid=call.sid //) as to input it into a MySQL database, I bump into an issue. (The 34 character ID has numbers and letters, so I define the datatype as VARCHAR).
begin
dbh = DBI.connect("DBI:Mysql:db_name:localhost",
"user", "pass")
dbh.do ("INSERT INTO calls (column_name)" #//Select the column to insert
"VALUES (incoming_Cid)") #Insert the 34 character string.
dbh.commit
puts "Customer SID has been recorded"
rescue
puts "A database occurred"
puts "Error code: #{e.err}"
puts "Error message: #{e.errstr}"
ensure
dbh.disconnect if dbh
end
Right here at the dbh.do ("INSERT INTO calls " line if I put the incoming_Cid variable in the VALUES() instead of seeing a 34-char-string, like CA9321a83241035b4c3d3e7a4f7aa6970d, I literally see 'incoming_Cid' appear in the database when I execute select * in calls.
How can I resolve this issue?

You need to use string interpolation: "VALUES (#{#incoming_Cid})"

Related

Stuck trying to display info on a CLI from an API that uses a hash and a nested hash

Trying to display second level information about characters from this Futurama API.
Currently using this code to get information:
def self.character
uri = URI.parse(URL)
response = Net::HTTP.get_response(uri)
data = JSON.parse(response.body)
data.each do |c|
Character.new(c["name"], c["gender"], c["species"], c["homePlanet"], c["occupation"], c["info"], c["sayings"])
end
end
I'm then stuck either returning (gender and species) from the nested hash (if character id > 8) or the original hash (character id < 8) when using this code:
def character_details(character)
puts "Name: #{character.name["first"]} #{character.name["middle"]} #{character.name["last"]}"
puts "Species: #{character.info["species"]}"
puts "Occupation: #{character.homePlanet}"
puts "Gender: #{character.info["gender"]}"
puts "Quotes:"
character.sayings.each_with_index do |s, i|
iplusone = i + 1
puts "#{iplusone}. #{s} "
end
end
Not sure where or what logic to use to get the correct information to display.
Maybe you have a problem when save c['info] in Character.new(c["name"], c["gender"], c["species"], c["homePlanet"], c["occupation"], c["info"], c["sayings"])
I'm running your code and I see info does not exist in the response of API, the gender should be accessed in character.gender
irb(main):037:0> character.gender
=> "Male"
irb(main):039:0> character.species
=> "Human"
I don't understand this comment: (if character id > 8) or the original hash (character id < 8) Can you explain us what u need do?

JSON no longer parsable after being sent through TCP in Ruby

I've created a basic client and server that pass a string, which I've changed to JSON instead. But the JSON string is only parsable before it gets sent through TCP. After it's sent, the string version is identical (after a chomp), but on the server side it no longer processes the JSON correctly. Here is some of my code (with other bits trimmed)
Some of the client code
require 'json'
require 'socket'
foo = {'a' => 1, 'b' => 2, 'c' => 3}
puts foo.to_s + "......."
foo.to_json
puts foo['b'] # => outputs the correct '2' answer
client = TCPSocket.open('localhost', 2000)
client.puts json
client.close;
Some of the server code
require 'socket'
require 'json'
server = TCPServer.open(2000)
while true
client = server.accept # Accept client
response = client.gets
print response
response = response.chomp
response.to_json
puts response['b'] # => outputs 'b'
end
The output 'b' should be '2' instead. How do I fix this?
Thanks
In your server you wrote response.to_json. This turns a string to JSON, then throws it away. And I don't like the .chomp, either.
Try
response = client.gets
hash = JSON.parse(response)
Now hash is a Ruby Hash object with your data in it, and hash['b'] should work correctly.
The problem is that .to_json does not parse JSON inside a string and replace itself with the result. It is used to convert the string into a format that is an acceptable JSON value.
require 'json'
string = "abc"
puts string
puts string.to_json
This will output:
abc
"abc"
The method is added to the String class by the JSON generator and it uses it internally to generate the JSON document.
But why does your response['b'] return "b"?
Because Ruby strings have a method called [] that can be used to:
Return a substring: "abc"[0,2] => "ab"
Return a single character from index: "abc"[1] => "b"
Return a substring if the string contains it: "abc"["bc"] => "bc", "abc"["fg"] => nil
Return a regexp match: "abc"[/^a([a-z])c/, 1] => "b"
and possibly some other ways I can't think of right now.
So this happens because your response is a string that has the character "b" in it:
response = "something with a b"
puts response["b"]
# outputs b
puts response["x"]
# outputs a blank line because response does not contain "x".
Instead of .to_json your code has to call JSON.parse or JSON.load:
data = JSON.parse(response)
puts data['b']

Ruby Mysql2 Client not taking backslash while insert

We are using production and staging databases in our application.
Our requirement is to insert all the records to staging database when ever a record is added in production database, so that both the servers are consistent and same data.
I have used Mysql2 client pool to connect to staging server and insert the record that is added to production.
here is my code:
def create
#aperson = Person.new
#person = #aperson.save
if #person && Rails.env == "production"
#add_new_person_to_staging
client = Mysql2::Client.new(:host => dbconfig[:host], :username => dbconfig[:username], :password => dbconfig[:password], :database => dbconfig[:database])
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values ("myname" , "\.myregex\." , "ns" );')
end
end
Here "#person_result" record is inserted to mysql table but the "regex" column eliminates "\" slashes.
like : user_name = myname, regex = .myregex., code = ns
when I manually execute the "Insert" query in mysql command line it inserts as it is along with \ slash. but not through "client.query"
Why does \ slash is eliminated. please help me here.
Thanks.
\ is likely being removed by the MySQL2 client as part of a SQL injection protection preprocessor.
Have you looked at trying either a double backslash or using the escape method to properly escape the string?
Try using this
#person_result = client.query('INSERT INTO user_types(user_name, regex, code) Values (myname , "\."+myregx+".\" , ns )')

Failed to insert value into tables in Ruby Mysql

I am trying to use Ruby to insert values into MySQL on localhost. The value i want to insert is the result from Twitter search. My program can successfully write the result to a file, so now i want to insert the result to MySQL. Here is part of my code:
results = #search.perform("yahoo", 100)
client = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "123", :database => "db1")
results.map do |status|
insert = client.query ("INSERT INTO table1 (fromuser, tweet) VALUES (#{status.from_user},#{status.text})")
end
The error is "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 " tweet " at line 1 (Mysql2::Error).
What caused the error?
Another problem i have found is that when i used following code to insert value to MySQL ,i got another error: "Unknown column 'a' in 'field list' (Mysql::ServerError::BadFieldError)"
require 'mysql'
require 'rubygems'
sql = Mysql.real_connect("localhost", "root", "123", "db1")
st1 = "a"
st2 = "b"
user_string = "(#{st1},#{st2})"
query="INSERT INTO table1 (fromuser, tweet) VALUES" + user_string
sql.query(query)
I want to insert "a" and "b" into table.
How to solve this?
Thanks in advance,
Like Andrew said, you definitely want to escape your data.
I think you also need to quote the values:
insert = client.query("INSERT INTO tweets (from_user, tweet_text)
VALUES ('#{client.escape(status.from_user)}',
'#{client.escape(status.text)}')")
You need to use CREATE TABLE to create a table in your database to insert the data into. At the moment you are saying you want to insert the data into the database name ("db1") itself.
Also, you must escape your data first:
insert = client.query("INSERT INTO tweets (from_user, tweet_text)
VALUES (#{client.escape(status.from_user)},
#{client.escape(status.text)})")

export to csv using fastercsv and CSV::Writer (Ruby on Rails)

What am I trying to do: export data to csv.
I have a form which allows user to select the format (from a drop down menu). So based on the selection of the format the ouput is displayed using a ajax call. Works fine for html but when I select the format as csv I don't see any pop up on the screen (asking to save or open the file) and neither any file gets downloaded directly.
I tried using Fastercsv (but the problem is that I don't see any pop up asking me whether I want to save or open the file) and CSV::Writer where I get this error message on the console.
NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.bytesize):
actionpack (2.3.4) lib/action_controller/streaming.rb:142:in `send_data'
Code using Fastercsv:
def export_to_csv
csv_string = FasterCSV.generate(:col_sep => ",") do |csv|
members = ["Versions / Project Members"]
members_selected.each {|member| members << Stat.member_name(member)}
Stat.project_members(project).each {|user| members << user.name}
csv << ["some text", "text 2", "text 3"]
end
return csv_string
end
and this is how I am sending the data:
send_data(export_to_csv,:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment", :filename => "filename.csv")
I see the response as "some text, text 2, text 3" in the firebug console but no pop up asking whether I want to save or open the file.
This is what I am doing using CSV::Writer:
def export_to_csv
report = StringIO.new
CSV::Writer.generate(report, ',') do |csv|
csv << ['c1', 'c2']
end
end
and call it as:
send_data(export_to_csv,:type => 'text/csv; charset=iso-8859-1; header=present',
:disposition => "attachment", :filename => "filename.csv")
This is the error which is thrown on the console:
NoMethodError (You have a nil object when you didn't expect it!
The error occurred while evaluating nil.bytesize):
actionpack (2.3.4) lib/action_controller/streaming.rb:142:in `send_data'
send_data is trying to reference an object that is out of scope. Check your closing 'end' statement