PackageDescription | Mojo::mysql is a tiny wrapper around DBD::mysql and DBD::MariaDB that makes
at http://www.mysql.org and at https://mariadb.org/ a lot of fun to use
with the at http://mojolicio.us real-time web framework.
The two DBD drivers are compatible with both MySQL and MariaDB, but they
offer different options. DBD::MariaDB should have better unicode support
though and might become the default in the future.
Database and handles are cached automatically, so they can be reused
transparently to increase performance. And you can handle connection
timeouts gracefully by holding on to them only for short amounts of time.
use Mojolicious::Lite;
use Mojo::mysql;
helper mysql =>
sub { state $mysql = Mojo::mysql->strict_mode('mysql://sri:s3cret@localhost/db') };
get '/' => sub {
my $c = shift;
my $db = $c->mysql->db;
$c->render(json => $db->query('select now() as time')->hash);
};
app->start;
While all I/O operations are performed blocking, you can wait for long
running queries asynchronously, allowing the Mojo::IOLoop event loop to
perform other tasks in the meantime. Since database connections usually
have a very low latency, this often results in very good performance.
Every database connection can only handle one active query at a time, this
includes asynchronous ones. So if you start more than one, they will be put
on a waiting list and performed sequentially. To perform multiple queries
concurrently, you have to use multiple connections.
my $db = $mysql->db;
$db->query('select sleep(5)' => sub {...});
$db->query('select sleep(5)' => sub {...});
$mysql->db->query('select sleep(5)' => sub {...});
$mysql->db->query('select sleep(5)' => sub {...});
All cached database handles will be reset automatically if a new process
has been forked, this allows multiple processes to share the same
Mojo::mysql object safely. |