mojolicious lite 中的催眠蟾蜍辅助函数

hypnotoad helper function in mojolicious lite

Mojolicious::Lite 应用程序可以与 morbo 一起使用,但不能与 hypnotoad 一起使用。

my $dbh = DBI->connect("dbi:mysql:dbname=xxx", "uname", "pass",
    { AutoCommit =>  0, mysql_enable_utf8 => 1},  )
    or die "Couldn't connect to database: ", $DBI::errstr;

helper db => sub { $dbh };
get '/xxx' => sub {
    my $sth = $self->db->prepare("insert into posts values(?,?,?,?,?,?)");
    $sth->execute('xxx', 'xxx', 'xxx', 'xxx', 'xxx', 'xxx');
    $sth->finish();
    $self->db->commit;
};

当 运行 使用 hypnotoad 时,应用程序的其余部分可以正常工作,但它不是 reading/writing 数据 to/from 数据库。请帮助我编写适用于 hypnotoad

的代码

你可以像这样使用DBIx::Connector

use strict;
use warnings;
use Mojolicious::Lite;
use DBIx::Connector;

helper connector => sub { 
    state $db = DBIx::Connector->new(sprintf('dbi:mysql:host=%s:database=%s',@{  $config->{mysql_database}}{qw[host db]}),@{$config->{mysql_database}}{qw[user password]}) or die "Could not connect";
};

helper mysql => sub { shift->connector->dbh };

post '/login' => sub {
    my $c = shift;

    my $user = $c->param('user_email');
    my $password = $c->param('password');

    my $sth = $c->mysql->prepare_cached('SELECT * FROM users WHERE user_email = ?') or $c->app->log->debug($DBI::errstr);

    $sth->execute($user);

    my $row = $sth->fetchrow_arrayref;

    $sth->finish;

    ## more code
};

当 hypnotoad 运行 作为守护进程(因此,分叉)时,数据库连接丢失。

我使用了数据库插件:

use Mojolicious::Plugin::Database;

在启动中:

sub startup {
  my $self = shift;

  # Load configuration from hash returned by config file
  my $config = $self->plugin('Config');

  $self->plugin( 'database', {
                     dsn => $config->{dsn},
                     username => $config->{user},
                     password => $config->{password},
                     options => {
                        RaiseError => 0,
                        mysql_auto_reconnect => 1,
                        AutoCommit => 1,
                        PrintError         => 0,
                        PrintWarn          => 0,
                     },
                     helper => 'db'
                });
}

最重要的是mysql_auto_reconnect!!!那解决了我的问题。