简体   繁体   中英

How to store and get perl dbi connection on different ajax request action in same perl script

I have a perl script in which I have created a dbConnection subroutine to connect to a mysql database like below. I am calling this subroutine on ajax action and storing database connection in $vb_db variable. After making connection, I am making another ajax request to dataImport subroutine where I need $vb_db connection to execute prepare statement. But on second ajax call for dataImport subroutine, I am not getting any value in $vb_db variable and failed query execution.

my $vb_db;
sub dbConnection {  
    my $db_host = $FORM{db_host};
    my $database = $FORM{database};
    my $db_user = $FORM{db_user};
    my $db_password = $FORM{db_password};       
    $vb_db = DBI->connect("DBI:mysql:$database;host=$db_host", $db_user, $db_password);

}

sub dataImport {
       my $records = $vb_db -> prepare("SELECT nodeid, title, description FROM node");
}

How can I get $vb_db value on second ajax call. Please help.

If you are doing one ajax request to setup the connection, and then you are doing a second ajax call to run dataImport, it will never work unless you are somehow caching the db connection on the server side. With cgi, the program starts, services the request and then exits. That means your DBI connections go out of scope and get reaped (since perl exits). You need to 1. Create the db connection on every request (and as mpapec says, store the user/pass etc so that you can do this) or 2. run as a persistent application via one of the many perl web frameworks such as Catalyst/Mojo/Dancer and have some type of dbi connection cache/pool.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM