in reply to Re: Data insert into SQL Server?
in thread Data insert into SQL Server?
Here is another approach, by using the file record separator ($/) to actually a "record" in your data file. There are a few approaches to it, one approach requires to change the source data file to use two newlines between records; this is because $/ can't take a regex as input.
When $/ value is an empty string it will match \n\n+ or a paragraph.
Also, if you use a hash to generate a table to translate the description to the field number you can simply the script for maintaning and when adding/removing fields as well as generating a template in case your need to feed default values.
Disclosure: I don't have a SQL server to test the code, that's why I commented the code, I focused the attention on how the data is handled.
#!/usr/bin/perl use warnings; use strict; my %fields = ( 'Type' => 0, 'No.of students' => 1, 'No.of classes' => 2, 'No.of teachers' => 3, 'Hostel facility' => 4, ); my $dbh; #$dbh->do('DROP TABLE test1'); # uncomment after first run #my $sql = 'CREATE TABLE test1 ( # type char(5), # students int, # class int, # teachers int, # hostel char(10) )'; #$dbh->do($sql); my $sqli = 'INSERT INTO test1 VALUES (?,?,?,?,?)'; #my $sth = $dbh->prepare($sqli); my @record = (); local $/ = ""; foreach(<DATA>) { chomp; # Fix the type field if(!s/^\++School\(B\):Students\++/Type:BOYS/) { s/^\++School\(G\):Students\++/Type:GIRLS/; } my @arr = split /[\r\n]+/; foreach(@arr) { my ($key, $data) = split /\s*:\s*/; $record[$fields{$key}] = $data; } print "Inserting \"@record\"\n"; # $sth->execute(@record[0..4]); } __DATA__ +++++++++++School(B):Students+++++++++++ No.of students : 120 No.of classes:2 No.of teachers:5 Hostel facility:available +++++++++++School(G):Students+++++++++++ No.of students:300 No.of classes:3 No.of teachers:10
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^3: Data insert into SQL Server?
by poj (Abbot) on Aug 08, 2011 at 18:21 UTC |