Execute SQL file in Perl

前端 未结 4 384
一向
一向 2020-12-10 17:53

We have a Perl script which runs a SQL and puts data in the table. Now instead of supplying a single SQL statement, we want to pass bunch of them putting them together in a

相关标签:
4条回答
  • 2020-12-10 18:34

    Not exactly sure what you want...

    Once you create a DBI object, you can use it over and over again. Here I'm reading SQL statement after SQL statement from a file and processing each and every one in order:

    use DBI;
    
    my $sqlFile = "/home/user1/tools/mytest.sql"
    
    my $dbh = DBI::Connect->new($connect, $user, $password)
        or die("Can't access db");
    
    # Open the file that contains the various SQL statements
    # Assuming one SQL statement per line
    
    open (SQL, "$sqlFile")
        or die("Can't open file $sqlFile for reading");
    
    # Loop though the SQL file and execute each and every one.
    while (my $sqlStatement = <SQL>) {
       $sth = dbi->prepare($sqlStatement)
          or die("Can't prepare $sqlStatement");
    
       $sth->execute()
          or die("Can't execute $sqlStatement");
    }
    

    Notice that I'm putting the SQL statement in the prepare and not the file name that contains the SQL statement. Could that be your problem?

    0 讨论(0)
  • 2020-12-10 18:36

    Here is how I've done it. In my case I dont assume one SQL per line and I assume, my example is a bit better :)

    sub get_sql_from_file {
        open my $fh, '<', shift or die "Can't open SQL File for reading: $!";
        local $/;
        return <$fh>;
    };
    
    my $SQL = get_sql_from_file("SQL/file_which_holds_sql_statements.sql");
    my $sth1 = $dbh1->prepare($SQL);
    $sth1->execute();
    
    0 讨论(0)
  • 2020-12-10 18:37

    You don't need perl for this at all. Just use the mysql command line client:

    mysql -h [hostname] -u[username] -p[password] [database name] < /home/user1/tools/mytest.sql

    replace the [variables] with your information.

    Note no space after -u or -p. If your mysql server is running on the same machine you can omit -h[hostname] (it defaults to localhost)

    0 讨论(0)
  • 2020-12-10 18:46

    There is a sort of workaround for DDL. You need to slurp SQL file first and then enclose it's contents into BEGIN ... END; keywords. Like:

    sub exec_sql_file {
        my ($dbh, $file) = @_;
    
        my $sql = do {
            open my $fh, '<', $file or die "Can't open $file: $!";
            local $/;
            <$fh>
        };
    
        $dbh->do("BEGIN $sql END;");
    }
    

    This subroutine allows to run DDL (SQL) scripts with multiple statements inside (e.g. database dumps).

    0 讨论(0)
提交回复
热议问题