Jump to content

Ruby & Mysql

- - - - -

This topic has been archived. This means that you cannot reply to this topic.
3 replies to this topic

#1
Minky

Minky

    Newbie

  • Members
  • Pip
  • 5 posts
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


#2
azad007

azad007

    Newbie

  • Members
  • Pip
  • 5 posts
I can't understand that where is the problem.

#3
unit2code

unit2code

    Newbie

  • Members
  • Pip
  • 2 posts
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";


#4
Arctic Fire

Arctic Fire

    Learning Programmer

  • Members
  • PipPipPip
  • 48 posts
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.