flutter 操作mysql

引入模块

dependencies:

flutter:

sdk: flutter

mysql1: ^0.20.0

mysql helper 的代码

dart 复制代码
import 'dart:async';  
import 'package:mysql1/mysql1.dart';  
  
class MySqlHelper {  
  static const _host = 'localhost';  
  static const _port = 3333;  
  static const _user = 'user';  
  static const _db = 'table';  
  static const _password = 'pass';  
  
  MySqlConnection? _connection;  
  
  MySqlHelper() {  
    _init();  
  }  
  
  Future<void> _init() async {  
    try {  
      _connection = await MySqlConnection.connect(ConnectionSettings(  
        host: _host,  
        port: _port,  
        user: _user,  
        db: _db,  
        password: _password,  
      ));  
    } catch (e) {  
      // Handle the exception appropriately, e.g., log the error or rethrow.  
      throw Exception('Failed to connect to the database: $e');  
    }  
  }  
  
  Future<int?> create(String tableName, Map<String, dynamic> data) async {  
    if (_connection == null) {  
      throw Exception('Database connection is not initialized');  
    }  
  
    var columns = data.keys.join(', ');  
    var placeholders = List.generate(data.length, (index) => '?').join(', ');  
    var values = data.values.toList();  
  
    var query = 'INSERT INTO $tableName ($columns) VALUES ($placeholders)';  
    var result = await _connection!.query(query, values);  
    return result.insertId;  
  }  
  
  Future<List<Map<String, dynamic>>> read(String tableName) async {  
    if (_connection == null) {  
      throw Exception('Database connection is not initialized');  
    }  
  
    var query = 'SELECT * FROM $tableName';  
    var results = await _connection!.query(query);  
    return results.map((row) => Map.fromEntries(row.asMap().entries.map((e) => MapEntry(e.key.toString(), e.value)))).toList();  
  }  
  
  Future<void> update(String tableName, Map<String, dynamic> data, String whereColumn, dynamic whereValue) async {  
    if (_connection == null) {  
      throw Exception('Database connection is not initialized');  
    }  
  
    var sets = data.entries.map((e) => '${e.key} = ?').join(', ');  
    var values = data.values.toList()..add(whereValue);  
  
    var query = 'UPDATE $tableName SET $sets WHERE $whereColumn = ?';  
    await _connection!.query(query, values);  
  }  
  
  Future<void> delete(String tableName, String whereColumn, dynamic whereValue) async {  
    if (_connection == null) {  
      throw Exception('Database connection is not initialized');  
    }  
  
    var query = 'DELETE FROM $tableName WHERE $whereColumn = ?';  
    await _connection!.query(query, [whereValue]);  
  }  
  
  Future<void> close() async {  
    if (_connection != null) {  
      await _connection!.close();  
      _connection = null;  
    }  
  }  
}  
  
// 使用示例  
void main() async {  
  final helper = MySqlHelper();  
  
  // 等待数据库连接初始化完成  
  await Future.delayed(Duration(seconds: 2)); // 仍然使用延迟作为示例,实际中应该监听连接状态  
  
  try {  
    // 插入数据  
    int? insertId = await helper.create('your_table_name', {  
      'column1': 'value1',  
      'column2': 'value2',  
    });  
    print('Inserted row with ID: $insertId');  
  
    // 读取数据  
    List<Map<String, dynamic>> rows = await helper.read('your_table_name');  
    for (var row in rows) {  
      print(row);  
    }  
  
    // 更新数据  
    await helper.update('your_table_name', {  
      'column1': 'updated_value1',  
    }, 'id', insertId);  
  
    // 删除数据  
    await helper.delete('your_table_name', 'id', insertId);  
  } catch (e) {  
    print('An error occurred: $e');  
  } finally {  
    // 关闭数据库连接  
    await helper.close();  
  }  
}
dart 复制代码
// 使用示例  
void main() async {
  final helper = MySqlHelper();

  // 等待数据库连接初始化完成  
  await Future.delayed(Duration(seconds: 2)); // 仍然使用延迟作为示例,实际中应该监听连接状态  

  try {
    // 插入数据  
    int? insertId = await helper.create('your_table_name', {
      'column1': 'value1',
      'column2': 'value2',
    });
    print('Inserted row with ID: $insertId');

    // 读取数据  
    List<Map<String, dynamic>> rows = await helper.read('your_table_name');
    for (var row in rows) {
      print(row);
    }

    // 更新数据  
    await helper.update('your_table_name', {
      'column1': 'updated_value1',
    }, 'id', insertId);

    // 删除数据  
    await helper.delete('your_table_name', 'id', insertId);
  } catch (e) {
    print('An error occurred: $e');
  } finally {
    // 关闭数据库连接  
    await helper.close();
  }
}
相关推荐
骆晨学长4 分钟前
基于springboot的智慧社区微信小程序
java·数据库·spring boot·后端·微信小程序·小程序
@月落10 分钟前
alibaba获得店铺的所有商品 API接口
java·大数据·数据库·人工智能·学习
楠枬20 分钟前
MySQL数据的增删改查(一)
数据库·mysql
goTsHgo25 分钟前
从底层原理上解释 clickhouse 保证完全的幂等性
数据库·clickhouse
阿华的代码王国2 小时前
MySQL ------- 索引(B树B+树)
数据库·mysql
Hello.Reader2 小时前
StarRocks实时分析数据库的基础与应用
大数据·数据库
执键行天涯2 小时前
【经验帖】JAVA中同方法,两次调用Mybatis,一次更新,一次查询,同一事务,第一次修改对第二次的可见性如何
java·数据库·mybatis
liupenglove2 小时前
golang操作mysql利器-gorm
mysql·golang
yanglamei19623 小时前
基于GIKT深度知识追踪模型的习题推荐系统源代码+数据库+使用说明,后端采用flask,前端采用vue
前端·数据库·flask
叫我:松哥3 小时前
基于Python flask的医院管理学院,医生能够增加/删除/修改/删除病人的数据信息,有可视化分析
javascript·后端·python·mysql·信息可视化·flask·bootstrap