Execute SQL file in Perl

前端 未结 4 442
一向
一向 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 = ) {
       $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?

提交回复
热议问题