Advertisement
Guest User

Untitled

a guest
Dec 15th, 2016
90
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.69 KB | None | 0 0
  1. # This Perl script dumps a given Oracle database schema into a set of CSV
  2. # files. The files will be named for the tables, have column headers, and
  3. # will all appear in the current working directory.
  4. # Original script by Jason McIntosh <jmac@jmac.org>
  5. #
  6. # You will need:
  7. # * Perl 5
  8. # * DBD::Oracle all set up, and knowledge of what your DBI DSN string is.
  9. # * Text::CSV, available from CPAN
  10. #
  11. # Configuration:
  12. # Set the following three variables to your Oracle schema's DBI DSN string,
  13. # username, and password.
  14. my $dsn = 'dbi:Oracle:whatever';
  15. my $user = 'whatever';
  16. my $pass = 'whatever';
  17. # You don't need to edit anything below this line. Just run the script!
  18.  
  19. use warnings;
  20. use strict;
  21.  
  22. use DBI;
  23. use Text::CSV;
  24.  
  25. my $dbi = DBI->connect( $dsn, $user, $pass );
  26.  
  27. my $sth = $dbi->prepare( 'SELECT table_name FROM user_tables' );
  28. $sth->execute;
  29. while ( my $row = $sth->fetchrow_arrayref ) {
  30. dump_table( $row->[0] );
  31. }
  32.  
  33. sub dump_table {
  34. my ( $table_name ) = @_;
  35.  
  36. print "Dumping $table_name...\n";
  37.  
  38. my @column_names;
  39. my $column_name_sth = $dbi->prepare(
  40. "SELECT column_name FROM USER_TAB_COLUMNS "
  41. . "WHERE table_name = '$table_name'"
  42. );
  43. $column_name_sth->execute;
  44. while ( my $row = $column_name_sth->fetchrow_arrayref ) {
  45. push @column_names, $row->[0];
  46. }
  47.  
  48. my $csv = Text::CSV->new ( { binary => 1 } );
  49. $csv->eol ("\n");
  50.  
  51. open ( my $fh,
  52. ">:encoding(utf8)",
  53. "$table_name.csv"
  54. ) or die "$table_name.csv: $!";
  55.  
  56. $csv->print ( $fh, \@column_names );
  57.  
  58. my $data_sth = $dbi->prepare( "select * from $table_name" );
  59. $data_sth->execute;
  60. while ( my $row = $data_sth->fetchrow_arrayref ) {
  61. $csv->print( $fh, $row );
  62. }
  63. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement