2

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 运行时,应用程序的其余部分正在工作,但它没有从数据库读取/写入数据。请帮助我编写与 hypnotoad 一起使用的代码

4

2 回答 2

2

当 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!!!这解决了我的问题。

于 2019-12-19T16:55:34.557 回答
2

您可以像这样使用 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
};
于 2019-05-21T07:40:26.897 回答