Flutter连接MySQL云数据库

Flutter连接MySQL云数据库

  • Flutter连接MySQL云数据库
    • 使用mysql1插件
    • 调用mysql1插件
    • 将数据渲染至页面

Flutter连接MySQL云数据库

使用mysql1插件

在pub.dev上找到mysql1插件(点击前往),
添加mysql1插件到pubspec.yaml文件中:

mysql1: ^0.17.1

调用mysql1插件

首先在需要处引入包:

import 'package:mysql1/mysql1.dart' as mysql;

因为包中的Row会和布局中的Row控件冲突,所以这里务必重命名。

如何使用:

Future Database() async {
    var settings = new mysql.ConnectionSettings(
        host: 'rm-xxxxxx.mysql.rds.aliyuncs.com',  // 这里以阿里云DMS为例
        port: 3306,
        user: 'your username', 	// 更换用户名
        password: 'your psw',		//更换密码
        db: 'python_catch_info');
    var conn = await mysql.MySqlConnection.connect(settings);
    var result =
        await conn.query("select * from movie_info ORDER BY movie_rank limit 20");
    await conn.close();
    print(result);
  }

官方example:

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',
      password: 'secret'));

  // 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, age from users where id = ?', [result.insertId]);
  for (var row in results) {
    print('Name: ${row[0]}, email: ${row[1]} age: ${row[2]}');
  }

  // Update some data
  await conn.query('update users set age=? where name=?', [26, 'Bob']);

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

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

将数据渲染至页面

展示数据是用python爬的某站电影排行榜,简单实现效果如下:
PS:M1芯片能跑Android虚拟机是真滴舒服
Flutter连接MySQL云数据库_第1张图片

代码 垃圾如下:

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:mysql1/mysql1.dart' as mysql;

class TopMoviePage extends StatefulWidget {
  const TopMoviePage({Key key}) : super(key: key);

  @override
  _TopMoviePageState createState() => _TopMoviePageState();
}

class _TopMoviePageState extends State<TopMoviePage> {
  List movieList = new List();
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('电影排行榜'),
      ),
      body: ListView.builder(
        itemCount: movieList.length,
        itemBuilder: (context, index) => movieCard(index),
      ),
    );
  }

  Widget movieCard(int index) {
    var info = movieList[index];
    var imageUrl = movieList[index]['cover_url'].toString();
    var movieType = movieList[index]['types'].toString().replaceRange(
        movieList[index]['types'].toString().length - 1,
        movieList[index]['types'].toString().length,
        '');
    var movieActors = movieList[index]['actors'].toString().replaceRange(
        movieList[index]['actors'].toString().length - 1,
        movieList[index]['actors'].toString().length,
        '等');
    var moviePublicTime;
    if (!movieList[index]['release_date'].toString().contains('-')) {
      moviePublicTime = movieList[index]['release_date'].toString() + '年';
    } else {
      moviePublicTime =
          movieList[index]['release_date'].toString().replaceFirst('-', '年');
      moviePublicTime = moviePublicTime.replaceFirst('-', '月') + '日';
    }

    return Container(
      padding: EdgeInsets.symmetric(vertical: 10, horizontal: 16),
      margin: EdgeInsets.only(top: 10, left: 8, right: 8),
      decoration: BoxDecoration(
          borderRadius: BorderRadius.all(Radius.circular(10)),
          boxShadow: [
            BoxShadow(
                color: Color(0xffffffff),
                offset: Offset(0.0, 6.0),
                blurRadius: 0,
                spreadRadius: 0)
          ]),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Container(
              width: 45,
              height: 20,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                color: Colors.redAccent,
                borderRadius: BorderRadius.all(Radius.circular(3)),
              ),
              child: RichText(
                text: TextSpan(children: [
                  TextSpan(
                    text: 'No.',
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                  TextSpan(
                    text: info['movie_rank'].toString(),
                    style: TextStyle(fontSize: 12, color: Colors.white),
                  ),
                ]),
              )),
          SizedBox(
            height: 5,
          ),
          Row(
            mainAxisAlignment: MainAxisAlignment.spaceBetween,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              Container(
                width: 100,
                height: 150,
                child: Image.network(
                  imageUrl,
                  fit: BoxFit.fill,
                ),
              ),
              SizedBox(
                width: 10,
              ),
              Container(
                // height: 150,
                width: 250,
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.start,
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(
                      info['title'].toString(),
                      style: TextStyle(
                          fontSize: 22,
                          color: Colors.black,
                          fontWeight: FontWeight.bold),
                    ),
                    SizedBox(
                      height: 10,
                    ),
                    RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: '评分:',
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.w400),
                        ),
                        TextSpan(
                          text: info['score'].toString(),
                          style: TextStyle(fontSize: 16, color: Colors.black),
                        ),
                      ]),
                    ),
                    RichText(
                      text: TextSpan(children: [
                        TextSpan(
                          text: '时间:',
                          style: TextStyle(
                              fontSize: 16,
                              fontWeight: FontWeight.w400,
                              color: Colors.black),
                        ),
                        TextSpan(
                          text: moviePublicTime,
                          style: TextStyle(fontSize: 16, color: Colors.black),
                        ),
                      ]),
                    ),
                    RichText(
                      softWrap: true,
                      text: TextSpan(children: [
                        TextSpan(
                          text: '类型:',
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.w400),
                        ),
                        TextSpan(
                          text: movieType,
                          style: TextStyle(fontSize: 16, color: Colors.black),
                        ),
                      ]),
                    ),
                    RichText(
                      softWrap: true,
                      text: TextSpan(children: [
                        TextSpan(
                          text: '主演:',
                          style: TextStyle(
                              fontSize: 16,
                              color: Colors.black,
                              fontWeight: FontWeight.w400),
                        ),
                        TextSpan(
                          text: movieActors,
                          style: TextStyle(fontSize: 16, color: Colors.black),
                        ),
                      ]),
                    ),
                  ],
                ),
              )
            ],
          )
        ],
      ),
    );
  }

  Future Database() async {
    var settings = new mysql.ConnectionSettings(
        host: 'rm-xxxxxxxxxx.mysql.rds.aliyuncs.com',
        port: 3306,
        user: 'user',
        password: 'psw',
        db: 'python_catch_info');
    var conn = await mysql.MySqlConnection.connect(settings);
    var result = await conn
        .query("select * from movie_info ORDER BY movie_rank limit 20");
    await conn.close();
    setState(() {
      movieList = result.toList();
    });
  }

  @override
  void initState() {
    super.initState();
    Database();
  }
}

End

你可能感兴趣的:(dart,mysql,flutter)