Mysql.dart - MySQL client for Dart written in Dart

Related tags

Templates mysql.dart
Overview

Native MySQL client written in Dart for Dart

See example directory for examples and usage

Roadmap

  • Auth with mysql_native_password
  • Basic connection
  • Connection pool
  • Query placeholders
  • Transactions
  • Prepared statements (real, not emulated)
  • SSL connection
  • Auth using caching_sha2_password (default since MySQL 8)
  • Send data in binary form when using prepared stmts (do not convert all into strings)
  • Multiple resul sets

Usage

Create connection pool

final pool = MySQLConnectionPool(
    host: '127.0.0.1',
    port: 3306,
    userName: 'your_user',
    password: 'your_password',
    maxConnections: 10,
    databaseName: 'your_database_name', // optional,
  );

Query database

var result = await pool.execute("SELECT * FROM book WHERE id = :id", {"id": 1});

Print result

  for (final row in result.rows) {
    print(row.assoc());
  }

Prepared statements

This library supports real prepared statements (using binary protocol).

Prepare statement

var stmt = await conn.prepare(
  "INSERT INTO book (author_id, title, price, created_at) VALUES (?, ?, ?, ?)",
);

Execute with params

await stmt.execute([null, 'Some book 1', 120, '2022-01-01']);
await stmt.execute([null, 'Some book 2', 10, '2022-01-01']);

Deallocate prepared statement

await stmt.deallocate();

Transactions

To execute queries in transaction, you can use transactional() method on connection or pool object Example:

await pool.transactional((conn) async {
  await conn.execute("UPDATE book SET price = :price", {"price": 300});
  await conn.execute("UPDATE book_author SET name = :name", {"name": "John Doe"});
});

In case of exception, transaction will roll back automatically.

Tests

To run tests execute

dart test
Comments
  • Support for proper error handling while performing initial handshake

    Support for proper error handling while performing initial handshake

    I'm currently trying to connect my Windows Flutter app to a MySQL 8 server hosted on my local machine.

    I am able to connect to it via my console, but the same isn't true for the Flutter app. Later found out that this issue was mainly related to not having the correct IP for my device (it was earlier set to the IP of my phone for testing purposes).

    This was initially hard to detect, since no logs except a RangeError was thrown while reading the packets received from the MySQL server.

    Here are some logs for the same (have added some additional logging in the library code that might be helpful):

    flutter: Isconnected: false
    flutter: TypedDataView(cid: 152)
    flutter: protocolVersion: 255
    flutter: Server version: jHost 'REPLACED_WITH_XYZ' is not allowed to connect to this MySQL server
    [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: RangeError (byteOffset): Invalid value: Not in inclusive range 0..67: 72
    #0      _ByteDataView.getUint32 (dart:typed_data-patch/typed_data_patch.dart:4864:7)
    #1      new MySQLPacketInitialHandshake.decode (package:mysql_client/src/mysql_protocol/packet/packet_initial_handshake.dart:48:35)
    #2      new MySQLPacket.decodeInitialHandshake (package:mysql_client/src/mysql_protocol/mysql_packet.dart:112:49)
    #3      MySQLConnection._processInitialHandshake (package:mysql_client/src/mysql_client/connection.dart:261:32)
    #4      MySQLConnection._processSocketData (package:mysql_client/src/mysql_client/connection.dart:154:13)
    #5      MySQLConnection.connect.<anonymous closure> (package:mysql_client/src/mysql_client/connection.dart:113:17)
    #6      MySQLConnection.connect.<anonymous closure> (package:mysql_client/src/mysql_client/connection.dart:110:42)
    #7      _rootRunUnary (dart:async/zone.dart:1434:47)
    #8      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
    #9      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
    #10     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
    #11     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
    #12     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
    #13     _StreamController._add (dart:async/stream_controller.dart:648:7)
    #14     _StreamController.add (dart:async/stream_controller.dart:596:5)
    #15     _Socket._onData (dart:io-patch/socket_patch.dart:2314:41)
    #16     _rootRunUnary (dart:async/zone.dart:1442:13)
    #17     _CustomZone.runUnary (dart:async/zone.dart:1335:19)
    #18     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
    #19     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
    #20     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
    #21     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
    #22     _StreamController._add (dart:async/stream_controller.dart:648:7)
    #23     _StreamController.add (dart:async/stream_controller.dart:596:5)
    #24     new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1839:33)
    #25     _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
    #26     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
    #27     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
    
    flutter: Isconnected: false
    

    Having a better error handling mechanism by preferably going through some official documentation related would be really helpful to improve the library. (Reference: https://dev.mysql.com/doc/internals/en/packet-ERR_Packet.html)

    Please do let me know if I could help you'll with a PR for the same.

    Thanks for building this library!

    bug waiting feedback 
    opened by MHShetty 39
  • MySQLServerException [1159]: Got timeout reading communication packets

    MySQLServerException [1159]: Got timeout reading communication packets

    Here are the logs that I testing the main branch -

    [ERROR:flutter/lib/ui/ui_dart_state.cc(198)] Unhandled Exception: MySQLServerException [1159]: Got timeout reading communication packets
    #0      MySQLConnection._processSocketData (package:mysql_client/src/mysql_client/connection.dart:201:9)
    #1      MySQLConnection.connect.<anonymous closure> (package:mysql_client/src/mysql_client/connection.dart:113:17)
    #2      MySQLConnection.connect.<anonymous closure> (package:mysql_client/src/mysql_client/connection.dart:110:42)
    #3      _rootRunUnary (dart:async/zone.dart:1434:47)
    #4      _CustomZone.runUnary (dart:async/zone.dart:1335:19)
    #5      _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
    #6      _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
    #7      _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
    #8      _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
    #9      _StreamController._add (dart:async/stream_controller.dart:648:7)
    #10     _StreamController.add (dart:async/stream_controller.dart:596:5)
    #11     _Socket._onData (dart:io-patch/socket_patch.dart:2314:41)
    #12     _rootRunUnary (dart:async/zone.dart:1442:13)
    #13     _CustomZone.runUnary (dart:async/zone.dart:1335:19)
    #14     _CustomZone.runUnaryGuarded (dart:async/zone.dart:1244:7)
    #15     _BufferingStreamSubscription._sendData (dart:async/stream_impl.dart:341:11)
    #16     _BufferingStreamSubscription._add (dart:async/stream_impl.dart:271:7)
    #17     _SyncStreamControllerDispatch._sendData (dart:async/stream_controller.dart:774:19)
    #18     _StreamController._add (dart:async/stream_controller.dart:648:7)
    #19     _StreamController.add (dart:async/stream_controller.dart:596:5)
    #20     new _RawSocket.<anonymous closure> (dart:io-patch/socket_patch.dart:1839:33)
    #21     _NativeSocket.issueReadEvent.issue (dart:io-patch/socket_patch.dart:1322:14)
    #22     _microtaskLoop (dart:async/schedule_microtask.dart:40:21)
    #23     _startMicrotaskLoop (dart:async/schedule_microtask.dart:49:5)
    
    flutter: TimeoutException
    flutter: TimeoutException after 0:00:30.000000: Future not completed
    flutter: Isconnected: false
    Lost connection to device.
    
    

    I'll share the logs from the logging branch soon. Please do let me know if any additional information is required apart from that.

    Thanks for your valuable time @zim32!

    opened by MHShetty 28
  • TimeoutException

    TimeoutException

    E/flutter (13703): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: TimeoutException after 0:00:05.000000: Future not completed E/flutter (13703): E/flutter (13703): [ERROR:flutter/lib/ui/ui_dart_state.cc(209)] Unhandled Exception: Exception: MySQL error: Got timeout reading communication packets

    its the error code using example. can anyone help me about this?

    opened by emre13k 23
  • Connection timed out (OS Error: Connection timed out, errno = 110), address = 10.0.0.2, port = 38528) or/and Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 39328)

    Connection timed out (OS Error: Connection timed out, errno = 110), address = 10.0.0.2, port = 38528) or/and Connection refused (OS Error: Connection refused, errno = 111), address = 127.0.0.1, port = 39328)

    hi my app did work lasterday morning but evening didnt work i didnt change code

    this code lasterday did work but today or lasterday evening didnt work . im taking connection timeout error class MySql { Future getConnection() async { debugPrint("Connecting to mysql server...");

    // create connection
    final conn = await MySQLConnection.createConnection(
        host: "10.0.0.2",
        port: 3306,
        userName: "root",
        password: "*******",
        secure: false
        // optional
        );
    debugPrint(conn.connected.toString());
    await conn.connect();
    debugPrint('conneccted');
    return conn;
    

    } },,

    another error . host: "127.0.0.1" connection refused error

    opened by Emirgms 22
  • Multiple statements

    Multiple statements

    Multiple statements

    When I run the following sql:

    SELECT v.entity_id INTO @id FROM catalog_product_entity_varchar v JOIN catalog_product_entity p ON v.entity_id = p.entity_id WHERE v.attribute_id = '283' AND v.value = '889501092529' LIMIT 1;
    
    SELECT v.value INTO @ean FROM catalog_product_entity_varchar v WHERE v.entity_id = @id AND v.attribute_id = '283' LIMIT 1;
    
    (SELECT g.value INTO @image_front FROM catalog_product_entity_media_gallery g, catalog_product_entity_media_gallery_value gv WHERE g.entity_id IN (SELECT r.parent_id FROM catalog_product_relation r WHERE r.child_id = @id) AND g.value_id = gv.`value_id` AND (gv.position = '1') ORDER BY gv.position ASC) LIMIT 1;
    
    (SELECT g.value INTO @image_back FROM catalog_product_entity_media_gallery g, catalog_product_entity_media_gallery_value gv WHERE g.entity_id IN (SELECT r.parent_id FROM catalog_product_relation r WHERE r.child_id = @id) AND g.value_id = gv.`value_id` AND (gv.position = '2') ORDER BY gv.position ASC) LIMIT 1;
    
    SELECT @id, @ean, @image_front, @image_back 
    

    ...it failes. It also happened to me with mysql1 driver pub package. As stated the code runs fine in phpMyAdmin (and returns one result set). The error code lead to SO posts about needing to specify delimiter.

    When I adding it, it fails:

    DELIMITER ; SELECT v.entity_id INTO @id FROM catalog_product_entity_varchar v JOIN catalog_product_entity p ON v.entity_id = p.entity_id WHERE v.attribute_id = '283' AND v.value = '889501092529' LIMIT 1 ; DELIMITER
    

    While this code works fin everywhere:

    SELECT v.entity_id INTO @id FROM catalog_product_entity_varchar v JOIN catalog_product_entity p ON v.entity_id = p.entity_id WHERE v.attribute_id = '283' AND v.value = '889501092529' LIMIT 1 ;
    

    Is it supported to make more statements than one in the same conn.execute(sql) call? Also, any help understanding why it not seem to work in (2) Flutter mysql drivers but works in phpMyAdmin would be appreciated.

    enhancement waiting feedback 
    opened by Lelelo1 17
  • fix inTransaction flg handle

    fix inTransaction flg handle

    I use this package for private projects. When I tried to use transaction, encountered a control I did not expect.

    Isn't COMMIT after _inTransaction = false; ...? It is possible that the intent of the control is not properly understood.

    Thanks for the great package. I support the long term development of this package.

    The following expressions are also possible.

    try {
      final result = await callback(this);
      await execute("COMMIT");
      return result;
    } catch {
      await execute("ROLLBACK");
      rethrow;
    } finally {
      _inTransaction = false;
    }
    
    opened by yamarkz 10
  • Decode values

    Decode values

    Hello,

    Currently all values returned are of type String. I understand the type int is provided so it would be possible to convert the values to their Dart type, however is there a built in utility to do this?

    opened by Ehesp 10
  • map SQL dates and times to DateTime

    map SQL dates and times to DateTime

    I have tested this just for my simple use case. @zim32 I can add some more tests for column types in this PR if general approach in this change is OK. This change is not backward compatible (typedAssoc will return different types) fixes #12

    opened by fsw 9
  • Issue generating a singleton

    Issue generating a singleton

    Maybe it is the state of the connection that is throwing this error. But get_it package will not load the connection properly. I removed the following reference from get_it and it immediately started:

      getItInstance.registerSingleton<MySQLConnection>(await initMysql());
    

    It looks like you already have a connection established as. a singleton and it is not letting me connect through a global pool. I have to use the example method of connecting only and call conn every time I want to make a call.

    Can you remove the singleton?

    opened by gumdum 8
  • Throw MySQLException rather than Exception

    Throw MySQLException rather than Exception

    Just trying to adapt your library into my package simple_mysql_orm.

    Firstly thanks for the work.

    One issue I note is that you throw a generic Exception class from the libraries.

    I'm wondering if you would consider changing this it a more specific class such as MySQLException as this makes it easier to catch and differentiate from other possible exceptions.

    enhancement waiting feedback 
    opened by bsutton 6
  • MySQLServerException [3988]: Conversion from collation utf8_general_ci into utf8mb4_general_ci impossible for parameter,

    MySQLServerException [3988]: Conversion from collation utf8_general_ci into utf8mb4_general_ci impossible for parameter,

    I am trying to get mysql to support emoji, but I get the above error when I insert data after configuring the server, is this because the client does not support it?  Can you give me some suggestions?  Thank you.

    my client config like this:

    _pool = MySQLConnectionPool(
          host: "127.0.0.1",
          port: 3306,
          userName: "name",
          password: "password",
          databaseName: "database",
          maxConnections: 16,
          collation: 'utf8mb4_general_ci',
        );
    
    opened by lhzmrl 5
  • MySQLClientException: Can not connect: status is not fresh

    MySQLClientException: Can not connect: status is not fresh

    hello, you did a great job on this lib, thank you

    From time to time I got this exception:

    MySQLClientException: Can not connect: status is not fresh
    package:mysql_client/src/mysql_client/connection.dart 116  MySQLConnection.connect
    

    may you please suggest a good way to manage the connection? and is there any getter method to check _state of the connection ?

    opened by booper 12
  • Data passing

    Data passing

    Hello. I would like to be able to retrieve the rows of a specific column and pass them to a list of String. How can I proceed?

    var res = await conn.execute('SELECT * FROM COMMERCIALS');
    
      for(final row in res.rows) {
        row.assoc()["NOM_COMMERCIAL"];
      }
    
    opened by AxelCope 0
  • How to pass empty password

    How to pass empty password

    await MySQLConnection.createConnection( host: '127.0.0.1', port: 3306, userName: 'root', password: 'root', databaseName: 'coba_dart_mysql', secure: false, );

    hi, thank you for making this excellent package, i just wanna ask, for connection sometime our local mysqldb not require the password, how to handle this case? thx

    opened by sulthanalihsan 2
  • I have TimeoutException error

    I have TimeoutException error

    Hi zim, Im using this package in localhost no problem but i need connect remote database i have this error,remote databe is phpmyadmin host and port are true but i cant connect i need your help pls

    class MySql {
      Future<MySQLConnection> getConnection() async {
        debugPrint("Connecting to mysql server...");
        final conn = await MySQLConnection.createConnection(
            host: '185.106.208.225', port: 8880, userName: "admin", password: "password", secure: false);
        await conn.connect();
        debugPrint('bağlandı');
        return conn;
      }
    }
    

    I/flutter (12322): Connecting to mysql server... I/flutter (12322): ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── I/flutter (12322): │ #0 MySQLConnection.createConnection package:mysql_client/…/mysql_client/connection.dart:87 I/flutter (12322): │ #1 MySql.getConnection package:inncrea/data_helper/data_helper.dart:9 I/flutter (12322): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ I/flutter (12322): │ 🐛 Establishing socket connection I/flutter (12322): └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── I/flutter (12322): ┌─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── I/flutter (12322): │ #0 MySQLConnection.createConnection package:mysql_client/…/mysql_client/connection.dart:89 I/flutter (12322): │ #1 <asynchronous suspension> I/flutter (12322): ├┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄┄ I/flutter (12322): │ 🐛 Socket connection established I/flutter (12322): └─────────────────────────────────────────────────────────────────────────────────────────────────────────────────────── E/flutter (12322): [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: TimeoutException after 0:00:05.000000: Future not completed E/flutter (12322):

    opened by Emirgms 3
  • Catching  SocketException

    Catching SocketException

    Hi. Thanks for your library.

    Sometime I got SocketException and even if its wrapped in try catch the error will be thrown and can not be handled, this makes not able to return any response correctly. please could you fix it, any workaround? SocketException: Operation timed out (OS Error: Operation timed out, errno = 60), address = ...

    opened by rebaz94 9
  • Unable to execute store procedure

    Unable to execute store procedure

    I have a store procedure which call some complex functions or other store procedure inside it. but unfortunately, it cannot be execute using this package.

    opened by leamlidara 1
Owner
null
A streaming client for the Komga self-hosted comics/manga/BD server targeting Android/iOS written in Dart/Flutter

Klutter A streaming client for the Komga self-hosted comics/manga/BD server targeting Android/iOS written in Dart/Flutter Background This is a project

Mark Winckle 58 Dec 7, 2022
a project-m36 websocket client written by flutter/dart

project_m36_websocket_client A Flutter web websocket client for Project-M36. It's also an attempt to bring algebraic datatypes into the Dart land. Pro

null 1 Jan 8, 2022
Unsplash Client App written using dart and flutter. (Work in progress)

Upsplash Unofficial Unsplash client written using dart and flutter Sreenshots Architecture The goal of this pattern is to make it easy to separate pre

Arslan 25 Sep 1, 2022
A cross-platform Fediverse client for micro-blogging services written in Flutter/Dart.

Kaiteki A 快適 (kaiteki) Fediverse client for microblogging instances, made with Flutter and Dart. Currently, Kaiteki is still in a proof-of-concept/alp

Kaiteki 141 Jan 5, 2023
An API Client for Discord, written in Dart.

discord_api_client An API Client for Discord, written in Dart. Features TODO: List what your package can do. Maybe include images, gifs, or videos. Ge

null 1 Feb 15, 2022
SurrealDB client written in pure dart. auto reconnect, typed functions

SurrealDB Client For Dart & Flutter SurrealDB client for Dart and Flutter. Quick Start import 'package:surrealdb/surrealdb.dart'; void main(List<Stri

Duhan BALCI 10 Dec 18, 2022
Unofficial 🐘 client written in 🎯

mastodon_dart The official Dart library for accessing the Mastodon API. Optionally use in conjunction with mastodon_flutter to build a Flutter Mastodo

Luke Pighetti 21 Dec 22, 2022
A client for Pleroma and Mastodon instances written using Flutter

Fedi for Pleroma and Mastodon Fedi is open-source client for Pleroma and Mastodon social networks written using Flutter. Pleroma and Mastodon are part

null 99 Dec 24, 2022
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package. Built after react apollo

Flutter GraphQL Table of Contents Flutter GraphQL Table of Contents About this project Installation Usage GraphQL Provider [Graphql Link and Headers]

Snowball Digital 45 Nov 9, 2022
A GraphQL client for Flutter, bringing all the features from a modern GraphQL client to one easy to use package.

GraphQL Flutter ?? Bulletin See the v3 -> v4 Migration Guide if you're still on v3. Maintenance status: Low. Follow #762 for updates on the planned ar

Zino & Co. 3.1k Jan 5, 2023
Passwall-mobile - A mobile client for PassWall API written with Flutter

passwall-mobile PassWall Mobile is a mobile client for PassWall API written with Flutter. Getting Started Clone the server app and build it. Install F

Abuzer Emre Osmanoğlu 104 Nov 22, 2022
Glance - A client for Reddit written in Flutter

Glance About the app Glance is an unofficial client for Reddit. However, it allows you to only browse through media posts such as photos and videos. I

Albert Wolszon 105 Nov 25, 2022
Datting-app-client - Social networking apps, FrontEnd written in Flutter

datting_social Social networking apps. FrontEnd written in Flutter. BackEnd writ

Đỗ Viết Hùng 39 Nov 13, 2022
Vrchat mobile client - VRChat Unofficial Mobile Client For Flutter

VRChatMC VRChatの非公式なAPIを利用したVRChatのモバイルクライアント Flutterで作成されたシンプルなUIが特徴的です iosビルドは

ふぁ 8 Sep 28, 2022
Dating-app-client - Social networking apps written in Flutter

datting_social Social networking apps. FrontEnd written in Flutter. BackEnd writ

Đỗ Viết Hùng 39 Nov 13, 2022
A Dart client for the NATS messaging system. Design to use with Dart and Flutter.

Dart-NATS A Dart client for the NATS messaging system. Design to use with Dart and flutter. Flutter Web Support by WebSocket client.connect(Uri.parse(

Chart Chongcharoen 32 Nov 18, 2022
Socketio dart server and client - Full Socket.io implementation using Dart Lang

Getting Started Step 1: Run dart_server.dart Step 2: Android Emulator has proble

Trần Thiên Trọng 1 Jan 23, 2022
A build system for Dart written in Dart

These packages provide libraries for generating, compiling and serving Dart code. Getting started with build_runner General FAQ Windows FAQ FAQ for Bu

Dart 676 Dec 24, 2022
Tool made in Dart that allows you to dynamically generate JSON files from data models written in Dart.

Dart JSON Generator Versión v1.1.1 Dart JSON Generator es una herramienta que permite generar archivos JSON a partir de mapas como modelos de datos en

Joinner Medina 7 Nov 23, 2022