Jump to content


Check out our Community Blogs

Register and join over 40,000 other developers!


Recent Status Updates

View All Updates

Photo
- - - - -

Ruby & Mysql

ruby mysql

  • Please log in to reply
3 replies to this topic

#1 Minky

Minky

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 21 April 2010 - 05:48 AM

Hi! I'm having some problems with a rubyscript that is accessing a mysql-database. When i'm trying to read ip-addresses from a textfile to an array and then base a sql-statement upon the array-elements I keep getting sql-statement errors due to ruby reads the textfile wrong and reads a newline in the first two entries in the file. Does anyone have a solution for this problem? =)

ip.txt
10.199.198.1
10.199.198.2
10.199.198.3
Error:
update Hosts set `TM-Me`=0 where IP="10.199.198.1
";
update Hosts set `TM-Me`=0 where IP="10.199.198.2
";
update Hosts set `TM-Me`=0 where IP="10.199.198.3
";
The SQL-statement should be:
update Hosts set `TM-Me`=0 where IP="10.199.198.1";
update Hosts set `TM-Me`=0 where IP="10.199.198.2";
update Hosts set `TM-Me`=0 where IP="10.199.198.3";
The Rubyscript:
#!/usr/bin/ruby -w

   require "mysql"

   begin
     dbh = Mysql.real_connect("10.199.198.5", "root", "cisco", "hostlist")

     f = open("C:\\Users\\Lars\\Desktop\\ip.txt")
     
     ip_array = []
     f.each_line { |line| ip_array << line }
     index = 0
     until index == ip_array.length
     dbh.query ("update Hosts set `TM-Me`=0 where IP=\"#{ip_array[index]}\";\n")
     printf ("update Hosts set `TM-Me`=0 where IP=\"#{ip_array[index]}\";\n")
     index += 1
     end
     
     f.close

   ensure
     dbh.close if dbh
   end

  • 0

#2 azad007

azad007

    CC Lurker

  • Just Joined
  • Pip
  • 5 posts

Posted 01 September 2010 - 12:40 AM

I can't understand that where is the problem.
  • 0

#3 unit2code

unit2code

    CC Lurker

  • Just Joined
  • Pip
  • 2 posts
  • Location:Central Ohio

Posted 15 October 2010 - 06:24 AM

I'm pretty new to MySQL, but from my understanding is that you don't need characters around the column names and the data to have quotes around them.
Such as the following...or was that (`TM-Me`) part of the name in the column?
update Hosts set TM-Me='0' where IP="10.199.198.1";

  • 0

#4 Arctic Fire

Arctic Fire

    CC Regular

  • Member
  • PipPipPip
  • 37 posts

Posted 09 March 2011 - 05:59 AM

Try using "line.strip!", it will remove the whitespaces (including newline character) from the string.

I'm new to Ruby, but I think you can just do:

f.each_line { |line| ip_array << line.strip! }

EDIT: Oh wow, I just realized how old this topic is.
  • 0





Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download