Dart的数据库操作

连接数据库

Dart连接数据库需要先从Pub下载sqljocky包
我新建了一个数据库,内容如下

Dart的数据库操作_第1张图片

连接数据库的代码如下

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  //创建一个连接池,host:连接地址,port:端口,user:用户名,password:密码,db:数据库名,max:最大并发数
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  //执行一条SQL语句
  pool.query("SELECT * FROM users");
}

控制台如果没有报错,那就说明连接成功了

使用下标读取结果

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  pool.query("SELECT * FROM users").then((results) {
    results.forEach((row) {
      //使用下标查询结果
      print('${row[1]},${row[3]}');
    });
  });
}

执行代码,控制台输出如下

Dart的数据库操作_第2张图片

使用字段读取结果

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  pool.query("SELECT * FROM users").then((results) {
    results.forEach((row) {
      //使用字段查询结果
      print('${row.name},${row.age}');
    });
  });
}

执行代码,控制台输出如下

Dart的数据库操作_第3张图片

准备SQL语句执行一次

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  //准备一个SQL语句
  pool.prepare('insert into users (name, age, email) values (?, ?, ?)').then((query) {
    //执行SQL语句
    query.execute(['咖啡', 22, '[email protected]']).then((result) {
      //一个插入语句的结果是空的,但是会有一个自动递增的id
      print("新用户的ID:${result.insertId}");
    });
  });
}

先查看一下控制台的输出

这里写图片描述

再看一下数据库

Dart的数据库操作_第4张图片

好了,我们成功插入了一条新数据

准备SQL语句批量执行

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  pool.prepare('insert into users (name, age, email) values (?, ?, ?)').then((query) {
    //批量执行SQL语句
    query.executeMulti([['绿豆', 18, '[email protected]'],
                        ['红豆', 17, '[email protected]'],
                        ['青豆', 17, '[email protected]']]).then((results) {
      //使用结果列表
      for (var result in results) {
        print("新用户的ID:${result.insertId}");
      }
    });
  });
}

先看看控制台输出

Dart的数据库操作_第5张图片

再看看数据库

Dart的数据库操作_第6张图片

执行一个事务

import 'package:sqljocky/sqljocky.dart';

main(List<String> arguments) {
  var pool = new ConnectionPool(host: 'localhost',port: 3306, user: 'root', password: '123456', db: 'test_mysql', max: 5);
  //创建一个事务
  pool.startTransaction().then((trans) {
    trans.query("DELETE FROM users WHERE id = '6'").then((result) {
      //提交事务
      trans.commit();
    });
  });
}

看看是否成功删除了id为6的用户

Dart的数据库操作_第7张图片

你可能感兴趣的:(Dart的数据库操作)