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();
  }
}
相关推荐
武子康1 小时前
Java-07 深入浅出 MyBatis - 一对多模型 SqlMapConfig 与 Mapper 详细讲解测试
java·开发语言·数据库·sql·mybatis·springboot
代码吐槽菌1 小时前
基于SSM的毕业论文管理系统【附源码】
java·开发语言·数据库·后端·ssm
路有瑶台2 小时前
MySQL数据库学习(持续更新ing)
数据库·学习·mysql
数字扫地僧2 小时前
WebLogic 版本升级的注意事项与流程
数据库
Summer不秃2 小时前
Flutter之使用mqtt进行连接和信息传输的使用案例
前端·flutter
lwprain2 小时前
常用docker应用部署,wordpress、mysql、tomcat、nginx、redis
mysql·docker·tomcat
旭日猎鹰2 小时前
Flutter踩坑记录(二)-- GestureDetector+Expanded点击无效果
前端·javascript·flutter
sunly_2 小时前
Flutter:AnimatedSwitcher当子元素改变时,触发动画
flutter
AiFlutter2 小时前
Flutter封装Coap
flutter
Viktor_Ye2 小时前
高效集成易快报与金蝶应付单的方案
java·前端·数据库