Last week, I received a small Case to import some employee information to the database. I opened the Excel file in the email. The original file format is as follows:
ID FirstName LastName
123 Jerry Chou
What I need to do is import the data to the database. Table columns in the database:
ID Name
My task is also simple:
1. Export the Excel file to CSV (Comma Separated Value ).
2. Remove the second comma of 123, Jerry, and Chou to form the format: 123, JerryChou.
3. Import 123 and JerryChou to the database.
Task 1It is very simple, and can be done with Exel.
Task 2, I wrote a Ruby script, as follows:
In_file = File.new('pi_user_import.csv ')
Out_file = File. new ("formatted_user.csv", "w ")
In_file.each_line do | line |
V1, v2, v3 = line. split (',')
Puts "# {v1.strip}, # {v2.strip} # {v3.strip} \ n"
Puts out_file.write ("# {v1.strip}, # {v2.strip} # {v3.strip} \ n ")
End
Task 3Is still a small script.
Require 'ci8'
Conn = OCI8.new ('dbuser', 'userpass', 'tnsname ')
Cursor = conn. parse ("insert into CPI_USER (ID, UNAME) VALUES (: 1,: 2 )")
In_file = File.new('formatted_user.csv ')
Row_num = 0
In_file.each_line do | line |
V1, v2 = line. split (',')
Puts "# {v1}, #{v2 }"
Cursor. bind_param (1, v1.strip)
Cursor. bind_param (2, v2.strip)
Cursor.exe c ()
Row_num = row_num + 1
End
Puts row_num.to_s + 'rows were processed .'
Cursor. close ()
Conn. commit
Conn. logoff
############## Imported Checking #####################
# Num_rows = conn.exe c ('select * from pi_user ') do | r |
# Puts r. join (',')
# End
# Puts num_rows.to_s + 'rows were processed .'
############## End Checking ####################### ###
Note: You can get the http://rubyforge.org/projects/ruby-oci8/ from: Ruby-OCI8.
Personal experience:
1. I haven't written Ruby's toy code for a long time, but it's easy to use Ruby to write a script to complete the task.
2. Ruby script supports Oracle well.
3. I remember hearing something like "iteration if I can't do it", but I don't remember who said it. This is true for some daily chores. Remind yourself that you cannot think like this when writing project code.