简体   繁体   English

如何在同一Perl脚本中的不同Ajax请求操作上存储和获取Perl DBI连接

[英]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. 我有一个perl脚本,在其中创建了dbConnection子例程以连接到如下所示的mysql数据库。 I am calling this subroutine on ajax action and storing database connection in $vb_db variable. 我在ajax操作上调用此子例程,并将数据库连接存储在$ vb_db变量中。 After making connection, I am making another ajax request to dataImport subroutine where I need $vb_db connection to execute prepare statement. 建立连接后,我向dataImport子例程提出了另一个Ajax请求,在该例程中,我需要$ vb_db连接来执行prepare语句。 But on second ajax call for dataImport subroutine, I am not getting any value in $vb_db variable and failed query execution. 但是在对dataImport子例程的第二次ajax调用中,我在$ vb_db变量中没有得到任何值,并且查询执行失败。

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. 如何在第二个ajax调用中获得$ vb_db值。 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. 如果您正在执行一个ajax请求来建立连接,然后您正在执行第二个ajax调用以运行dataImport,则除非您以某种方式在服务器端缓存数据库连接,否则它将永远无法工作。 With cgi, the program starts, services the request and then exits. 使用cgi,程序将启动,为请求提供服务,然后退出。 That means your DBI connections go out of scope and get reaped (since perl exits). 这意味着您的DBI连接超出范围并受到限制(因为perl退出)。 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. 您需要1.在每个请求上创建db连接(如mpapec所述,存储用户/密码等,以便您可以执行此操作)或2.通过许多perl Web框架之一(例如Catalyst)作为持久性应用程序运行/ Mojo / Dancer并具有某种类型的dbi连接缓存/池。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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