How to automate a large number of txt files to be imported from Perl to a SQL Server using DBI? -


i have attempted transfer 1 txt file sql server perl, need create db in sql combines hundreds of txt files. there automated way of doing save manually transferring txt files? insert attempt of coding 1 txt file. believe need use bulk insert achieve unsure code use. advice on problem appreciated, , if there anymore code wish see or specific thing forgot mention please comment , edit. thank you.

#!/usr/bin/perl -w use strict; use dbi; use carp;      # connect data source , handle connection. $dbh = dbi->connect('dbi:odbc:regressiondbs') ||     confess "connection failed: $dbi::errstr";      # query generates result set 1 record in it. $sql = "select 1 test_col"; $tablename = "regressiontable";  open(fh, "newregression.txt") || die "cant open file"; $sqlh = $dbh->prepare("insert regressiontable (ticker, tradedate, highprice, lowprice, tradeprice, totalvolume, totalvalue) values (?,?,?,?,?,?,?);") || confess $dbi::errstr; while (my $line = <fh> ) { $line =~/^(.*)(..)(..)$/; ($curticker, $wtradedate, $whighprice, $wlowprice, $wtradeprice, $wtotalvolume, $wtotalvalue);     $curticker=$1     #$wtradedate=     $whighprice=$2;     $wlowprice=$1;     #$wtradeprice=$1;     #$wtotalvolume=$1;     #$wtotalvalue=$4;  $sqlh->execute($curticker, $wtradedate, $whighprice, $wlowprice, $wtradeprice, $wtotalvolume, $wtotalvalue) || confess $dbi::errstr;  }  $sqlh->finish(); $dbh->disconnect(); 

ok, run

insert regressiontable (   ticker, tradedate, highprice, lowprice, tradeprice, totalvolume, totalvalue )  values (?, ?, ?, ?, ?, ?, ?) 

for every line in newregression.txt, , want multiple files. why not wrap code above in subroutine, insert_file(), call per file in loop...

my @files = qw(red.txt green.txt blue.txt); $file (@files) {   insert_file($file); } 

or if target table varies per file, define hash:

my %files = (   'red.txt'  => 'redtable',    'blue.txt' => 'bluetable' ); while ( ($file, $table) = each %files ) {   insert_file($file, $table); }; 

not sure how you'd use bulk insert given field separator in data file seems indeterminate (i.e. regex /(.*)(..)(..)/ defines field boundaries). may need use formatfile option. also, if generate bulk insert statement using dbi, aware user sql server runs must able read data files on filesystem (networked, local or otherwise).


Comments

Popular posts from this blog

c++ - CryptStringToBinary API behavior -

java.util.scanner - How to read and add only numbers to array from a text file -

iphone - Three second countdown in cocos2d -