Connecting to a MySQL or Maria DB server from Dart is very easy. We need just one package. The package we need is ‘mysql1’ which provides a MySQL client library for Dart. This package allows us to establish a connection with a MySQL server and execute queries. 

Package for MySQL

Create your pubspec.yaml and add mysql1 as a dependency.

name: mysql
description: A sample command-line application.
# version: 1.0.0
# homepage: https://www.example.com
# author: sminrana <[email protected]>

environment:
  sdk: '>=2.0.0 <3.0.0'

dependencies:
  mysql1: ^0.17.1

dev_dependencies:
  test: ^1.0.0

Run the following command

pub get

Dart Code

Once we have installed the’mysql1′ package, we can use the main function to define the necessary connection parameters, such as host, port, username, and password. After that, we can create a new instance of the ‘MySqlConnection’ class using these settings and establish a connection to the MySQL or Maria DB server. 

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', '[email protected]', 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 asynchronous dart main function is required due to the async call on line 7, here we must wait for await MySqlConnection to finish 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
Spread the love

Leave a comment

In this article

Index