准备:

在pub.dev上找到mysql1 (链接)
在pubspec.yaml里面引入依赖 mysql1: ^0.17.1
在这里插入图片描述

在需要使用的地方引入包

如果项目不存在包冲突,在删除导包import那行"as mysql"的同时请记得删除下面代码中的"mysql.",不然会报错
import ‘dart:async’;
import ‘package:mysql1/mysql1.dart’;
这里会遇到个坑,如果你的布局中用到Row,由于包里面的内容冲突可能会报错,改成import ‘package:mysql1/mysql1.dart’ as mysql;就可以了。

//连接数据库&查询
Future Database(yxcode) async{
  var settings = new mysql.ConnectionSettings(
      host: '你数据库的地址',
      port: 3306,
      user: '你的用户名',
      password: '密码',
      db: '数据库名'
  );
  var conn = await mysql.MySqlConnection.connect(settings);
  var userId = yxcode;
  var results = await conn.query('select code from yxcode where codeID = ?', [userId]);
  await conn.close();
  Fluttertoast.showToast(msg: '$results');
  print(results);
}

附官方demo

import 'dart:async';
import 'package:mysql1/mysql1.dart';

Future main() async {
  // Open a connection (testdb should already exist)
  final conn = await MySqlConnection.connect(ConnectionSettings(
      host: 'localhost', port: 3306, user: 'root', db: 'testdb'));

  // 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();
}
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐