Skip to content

Instantly share code, notes, and snippets.

@ledger123
Last active January 22, 2024 16:27
Show Gist options
  • Select an option

  • Save ledger123/4e3651cd11d65c8a7e5bbf4c9fa20936 to your computer and use it in GitHub Desktop.

Select an option

Save ledger123/4e3651cd11d65c8a7e5bbf4c9fa20936 to your computer and use it in GitHub Desktop.
Generate SQL statements from database
#!/usr/bin/perl
use strict;
use warnings;
use DBI;
my @tables = ( 'chart', 'curr', 'defaults' );
my $output_file = 'RMADE_DEU_Basiskontenplan-chart.sql';
my $db_name = 'ledger28';
my $db_host = 'localhost';
my $db_user = 'sql-ledger';
my $db_pass = '';
my $dbh = DBI->connect(
"dbi:Pg:dbname=$db_name;host=$db_host",
$db_user, $db_pass,
{
RaiseError => 1,
PrintError => 0,
}
);
open( my $output_fh, '>', $output_file ) or die "Could not open $output_file: $!";
foreach my $table (@tables) {
my $stmt = $dbh->prepare("SELECT * FROM $table");
$stmt->execute();
my @columns;
for my $col_info ( @{ $stmt->{NAME_lc} } ) {
push @columns, $col_info unless $col_info eq 'id';
}
while ( my $row = $stmt->fetchrow_hashref() ) {
my @values = map { defined $row->{$_} ? "'$row->{$_}'" : 'NULL' } @columns;
my $columns_str = join( ', ', @columns );
my $values_str = join( ', ', @values );
my $insert_sql = "INSERT INTO $table ($columns_str) VALUES ($values_str);";
print $output_fh "$insert_sql\n";
}
}
close $output_fh;
$dbh->disconnect;
print "SQL statements generated and saved to $output_file\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment