Mojo::mysql - Mojolicious and Async MySQL/MariaDB


  use Mojo::mysql;

  # Connect to a local database
  my $mysql = Mojo::mysql->strict_mode('mysql://username@/test');

  # Connect to a remote database
  my $mysql = Mojo::mysql->strict_mode('mysql://username:password@hostname/test');
  # MySQL >= 8.0:
  my $mysql = Mojo::mysql->strict_mode('mysql://username:password@hostname/test;mysql_ssl=1');

  # Use DBD::MariaDB instead of DBD::mysql
  my $mysql = Mojo::mysql->strict_mode('mariadb://username@/test');

  # Create a table
    'create table names (id integer auto_increment primary key, name text)');

  # Insert a few rows
  my $db = $mysql->db;
  $db->query('insert into names (name) values (?)', 'Sara');
  $db->query('insert into names (name) values (?)', 'Stefan');

  # Insert more rows in a transaction
  eval {
    my $tx = $db->begin;
    $db->query('insert into names (name) values (?)', 'Baerbel');
    $db->query('insert into names (name) values (?)', 'Wolfgang');
  say $@ if $@;

  # Insert another row and return the generated id
  say $db->query('insert into names (name) values (?)', 'Daniel')

  # Use SQL::Abstract::mysql to generate queries for you
  $db->insert('names', {name => 'Isabel'});
  say $db->select('names', undef, {name => 'Isabel'})->hash->{id};
  $db->update('names', {name => 'Bel'}, {name => 'Isabel'});
  $db->delete('names', {name => 'Bel'});

  # Select one row at a time
  my $results = $db->query('select * from names');
  while (my $next = $results->hash) {
    say $next->{name};

  # Select all rows blocking
  $db->query('select * from names')
    ->hashes->map(sub { $_->{name} })->join("\n")->say;

  # Select all rows non-blocking
  $db->query('select * from names' => sub {
    my ($db, $err, $results) = @_;
    $results->hashes->map(sub { $_->{name} })->join("\n")->say;

  # Concurrent non-blocking queries (synchronized with promises)
  my $now   = $db->query_p('select now() as now');
  my $names = $db->query_p('select * from names');
  Mojo::Promise->all($now, $names)->then(sub {
    my ($now, $names) = @_;
    say $now->[0]->hash->{now};
    say $_->{name} for $names->[0]->hashes->each;
  })->catch(sub {
    my $err = shift;
    warn "Something went wrong: $err";

  Mojo::IOLoop->start unless Mojo::IOLoop->is_running;


Mojo::mysql is a tiny wrapper around DBD::mysql and DBD::MariaDB that makes MySQL and MariaDB a lot of fun to use with the Mojolicious 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);


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.

  # Performed sequentially (10 seconds)
  my $db = $mysql->db;
  $db->query('select sleep(5)' => sub {...});
  $db->query('select sleep(5)' => sub {...});

  # Performed concurrently (5 seconds)
  $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.


Mojo::mysql inherits all events from Mojo::EventEmitter and can emit the following new ones.


  $mysql->on(connection => sub {
    my ($mysql, $dbh) = @_;

Emitted when a new database connection has been established.


Mojo::mysql implements the following attributes.


  $abstract = $mysql->abstract;
  $mysql    = $mysql->abstract(SQL::Abstract::mysql->new);

SQL::Abstract::mysql object used to generate CRUD queries for Mojo::mysql::Database.

  # Generate statements and bind values
  my ($stmt, @bind) = $mysql->abstract->select('names');


  my $bool = $mysql->auto_migrate;
  $mysql   = $mysql->auto_migrate($bool);

Automatically migrate to the latest database schema with "migrations", as soon as the first database connection has been established.

Defaults to false.


  $class = $mysql->database_class;
  $mysql = $mysql->database_class("MyApp::Database");

Class to be used by "db", defaults to Mojo::mysql::Database. Note that this class needs to have already been loaded before "db" is called.


  my $dsn = $mysql->dsn;
  $mysql  = $mysql->dsn('dbi:mysql:dbname=foo');

Data Source Name, defaults to dbi:mysql:dbname=test.


  my $max = $mysql->max_connections;
  $mysql  = $mysql->max_connections(3);

Maximum number of idle database handles to cache for future use, defaults to 5.


  my $migrations = $mysql->migrations;
  $mysql         = $mysql->migrations(Mojo::mysql::Migrations->new);

Mojo::mysql::Migrations object you can use to change your database schema more easily.

  # Load migrations from file and migrate to latest version

MySQL and MariaDB does not support nested transactions and DDL transactions. DDL statements cause implicit COMMIT. ROLLBACK will be called if any step of migration script fails, but only DML statements after the last implicit or explicit COMMIT can be reverted. Not all storage engines (like MYISAM) support transactions.

This means database will most likely be left in unknown state if migration script fails. Use this feature with caution and remember to always backup your database.


  my $options = $mysql->options;
  $mysql      = $mysql->options({mysql_use_result => 1});

Options for database handles, defaults to activating mysql_enable_utf8 (only for DBD::mysql), AutoCommit, AutoInactiveDestroy as well as RaiseError and deactivating PrintError. AutoCommit and RaiseError are considered mandatory, so deactivating them would be very dangerous.

mysql_auto_reconnect is never enabled, Mojo::mysql takes care of dead connections.

AutoCommit cannot not be disabled, use $db->begin to manage transactions.

RaiseError is enabled for blocking and disabled in event loop for non-blocking queries.

About mysql_enable_utf8:

  The mysql_enable_utf8 sets the utf8 charset which only supports up to 3-byte
  UTF-8 encodings. mysql_enable_utf8mb4 (as of DBD::mysql 4.032) properly
  supports encoding unicode characters to up to 4 bytes, such as 𠜎. It means the
  connection charset will be utf8mb4 (supported back to at least mysql 5.5) and
  these unicode characters will be supported, but no other changes.

See also


  my $password = $mysql->password;
  $mysql       = $mysql->password('s3cret');

Database password, defaults to an empty string.


  my $pubsub = $mysql->pubsub;
  $mysql     = $mysql->pubsub(Mojo::mysql::PubSub->new);

Mojo::mysql::PubSub should be considered an EXPERIMENT! See "DESCRIPTION" in Mojo::mysql::PubSub for more information.


  my $username = $mysql->username;
  $mysql       = $mysql->username('batman');

Database username, defaults to an empty string.


Mojo::mysql inherits all methods from Mojo::EventEmitter and implements the following new ones.


  $mysql = $mysql->close_idle_connections($keep);

Close all connections that are not currently active, or limit the number of idle connections to $keep.


  my $db = $mysql->db;

Get Mojo::mysql::Database object for a cached or newly created database handle. The database handle will be automatically cached again when that object is destroyed, so you can handle connection timeouts gracefully by holding on to it only for short amounts of time.


  $mysql = $mysql->from_string('mysql://user@/test');

Parse configuration from connection string.

  # Just a database

  # Username and database

  # Username, password, host and database

  # Username, domain socket and database

  # Username, database and additional options


  my $mysql = Mojo::mysql->new;
  my $mysql = Mojo::mysql->new(%attrs);
  my $mysql = Mojo::mysql->new(\%attrs);
  my $mysql = Mojo::mysql->new('mysql://user@/test');
  my $mysql = Mojo::mysql->new('mariadb://user@/test');

Construct a new Mojo::mysql object either from "ATTRIBUTES" and or parse connection string with "from_string" if necessary.

Using the "mariadb" scheme requires the optional module DBD::MariaDB version 1.21 (or later) to be installed.


  my $mysql = Mojo::mysql->strict_mode('mysql://user@/test');
  my $mysql = $mysql->strict_mode($boolean);

This method can act as both a constructor and a method. When called as a constructor, it will be the same as:

  my $mysql = Mojo::mysql->new('mysql://user@/test')->strict_mode(1);

Enabling strict mode will execute the following statement when a new connection is created:


The idea is to set up a connection that makes it harder for MySQL to allow "invalid" data to be inserted.

This method will not be removed, but the internal commands is subject to change.


You can set the DBI_TRACE environment variable to get some advanced diagnostics information printed to STDERR by DBI.


See also and


This is the class hierarchy of the Mojo::mysql distribution.


This project is highly inspired by Sebastian Riedel's Mojo::Pg.

Project Founder

Jan Henning Thorsen -


  • Adam Hopkins <>

  • Alexander Karelas <>

  • Curt Hochwender <>

  • Dan Book <>

  • Doug Bell <>

  • Florian Heyer <>

  • Hernan Lopes <>

  • Karl Rune Nilsen <>

  • Larry Leszczynski <>

  • Lucas Tiago de Moraes <>

  • Matt S Trout <>

  • Mike Magowan <>

  • Mohammad S Anwar <>

  • Rolf Stöckli <>

  • Sebastian Riedel <>

  • Svetoslav Naydenov <>

  • Svetoslav Naydenov <>

  • Tekki <>


Copyright (C) 2014-2019, Jan Henning Thorsen.

This program is free software, you can redistribute it and/or modify it under the terms of the Artistic License version 2.0.


Mojo::Pg Async Connector for PostgreSQL using DBD::Pg,,

Mojo::MySQL5 Pure-Perl non-blocking I/O MySQL Connector,,