I am trying to use Mojolicious database plugin, and find some difficulties. My first two pages of Google results about this topics are already visited. Scenario is very simple: connect to a db (mysql), fetch some data, display it. Here is an excerpt of the code:
use Mojolicious::Lite;
use Mojolicious::Plugin::Database;
# [...]
sub startup {
my $self = shift;
$self->plugin('database', {
dsn => 'dbi:MySQL:dbname=y',
username => $mysql_user,
password => $mysql_passwd,
helper => 'ydb',
});
};
get '/' => sub {
my $c = shift;
my $zz=$c->ydb->prepare("select count(*) from customers");
my $total=$zz->execute();
$c->ydb->bind_columns(\$total);
$c->ydb->fetch;
$c->session(customer=>$total);
$c->render(template => 'index');
};
but I received the error:
Can't locate object method "ydb" via package "Mojolicious::Controller"
I am surely missing some basics. Could someone point me in the right direction?
I never got the helper from the plugin working. I created my own helper in combination with Mojo::mysql.
use Mojolicious::Lite;
use Mojo::mysql;
sub startup {
my $self = shift;
}
helper ydb => sub {
my $c = shift ;
return Mojo::mysql->strict_mode('mysql://muziek:muziek@localhost/muziek')
};
get '/foo' => sub {
my $c = shift ;
my $db = $c->ydb->db;
my $row = $db->query("select count(*) COUNT from TITLE")->hash;
$c->render(text => "Hello from /foo. count=" . $row->{COUNT} );
};
app->start;