MySQL and Maria DB connection with Dart language

MySQL and Maria DB connection with Dart language

Connect to MySQL or Maria DB server from Dart is very easy. We just need a couple of packages.

Create your pubspec.yaml and add mysqli as a dependency. And run

pub get

Create a file name main.dart which looks like this

import 'dart:async';
import 'dart:io';

import 'package:mysql1/mysql1.dart';

Future main() async {
  final conn = await MySqlConnection.connect(ConnectionSettings(
      host: 'localhost', port: 3306, user: 'root', password: '1234', db: 'database_name'));


  // Create a table
  await conn.query(
      'CREATE TABLE users (id int NOT NULL AUTO_INCREMENT PRIMARY KEY, name varchar(255), email varchar(255), age int)');

  // Insert some data
  var result = await conn.query(
      'insert into users (name, email, age) values (?, ?, ?)',
      ['Bob', 'bob@bob.com', 25]);
  print('Inserted row id=${result.insertId}');

  // Query the database using a parameterized query
  var results = await conn
      .query('select name, email from users where id = ?', [result.insertId]);
  for (var row in results) {
    print('Name: ${row[0]}, email: ${row[1]}');
  }

  // Finally, close the connection
  await conn.close();
}

Here Future main async as an asynchronous dart main function which is required due to async call on line 7, here we must wait for await MySqlConnection to be finished its process.

Similarly we must wait for the task to be finished on line 12, we create a database table on this line.

Finally run the code by

dart main.dart