Flutter数据库操作插件mysql_utils的使用
Flutter数据库操作插件mysql_utils的使用
简介
mysql_utils
是一个帮助Flutter项目连接和操作MySQL数据库的插件。自2.0.0版本以来,该插件采用了更为稳定的 mysql_client
扩展库,并尽量保持与2.0.0之前版本方法的兼容性。
如果你在寻找SQLite的支持,可以尝试 sqlite_utils 插件。
Pub安装
可以通过 Pub安装页面 获取详细的安装步骤。
使用APIs
初始化连接
初始化参数相较于1.0有所变化,建议使用单例模式,并在使用后调用 close()
方法关闭数据库连接。
var db = MysqlUtils(
settings: {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'test',
'maxConnections': 10,
'secure': false,
'prefix': 'prefix_',
'pool': true,
'collation': 'utf8mb4_general_ci',
'sqlEscape': true,
},
errorLog: (error) {
print(error);
},
sqlLog: (sql) {
print(sql);
},
connectInit: (db1) async {
print('whenComplete');
}
);
查询操作
原生查询
注意这里的方法不同于1.0版本,2.0继承了 mysql_client
的方法。
var row = await db.query('select id from Product where id=:id or description like :description',{
'id':1,
'description':'%ce%'
});
print(row.toMap());
单条记录查询
var row = await db.getOne(
table: 'table',
fields: '*',
where: {'email': 'xxx@google.com'},
);
print(row);
多条记录查询
var row = await db.getAll(
table: 'table',
fields: '*',
where: {'id': ['>', 1]},
);
print(row);
数据操作
插入单条数据
await db.insert(
table: 'table',
insertData: {
'telphone': '+113888888888',
'create_time': 1620577162252,
'update_time': 1620577162252,
},
);
插入多条数据
await db.insertAll(
table: 'table',
insertData: [
{
'telphone': '13888888888',
'create_time': 1111111,
'update_time': 12121212,
'email': 'teenagex@dd.com'
},
{
'telphone': '13881231238',
'create_time': 324234,
'update_time': 898981,
'email': 'xxx@dd.com'
}
]
);
更新数据
await db.update(
table: 'table',
updateData: {
'telphone': '1231',
'create_time': 12,
'update_time': 12121212,
'email': 'teenagex@dd.com'
},
where: {'id':1},
);
删除数据
await db.delete(
table:'table',
where: {'id':1}
);
统计操作
计数
await db.count(
table: 'table',
fields: '*',
);
平均值
await db.avg(
table: 'table',
fields: 'price',
);
最小值
await db.min(
table: 'table',
fields: 'price',
);
最大值
await db.max(
table: 'table',
fields: 'price',
);
事务支持
遇到异常时,事务会自动回滚。
await db.startTrans();
await db.delete(table: 'user', where: {'id': 25}, debug: true);
//await db.delete(table: 'user1', where: {'id': 26}, debug: true);
await db.commit();
await db.close();
连接状态检查
var isAlive = await db.isConnectionAlive();
if (isAlive) print('mysql is isAlive');
示例Demo
以下是一个完整的示例demo,包含了插入、查询等基本操作:
import 'dart:async';
import 'dart:math';
import 'package:mysql_utils/mysql_utils.dart';
Future main() async {
var rng = new Random();
final db = MysqlUtils(
settings: {
'host': '127.0.0.1',
'port': 3306,
'user': 'root',
'password': 'root',
'db': 'test',
'maxConnections': 10,
'secure': false,
'prefix': 'su_',
'pool': false,
'collation': 'utf8mb4_general_ci',
},
errorLog: (error) {
print(error);
},
sqlLog: (sql) {
print(sql);
},
connectInit: (db1) async {
print('whenComplete');
},
);
// 插入数据
var res3 = await db.insert(
table: 'user',
insertData: {
'nickname': '中文测试-${rng.nextInt(100)}',
'telphone': '+113888888888',
'createTime': 1620577162252,
'updateTime': 1620577162252,
},
);
print(res3); // lastInsertID
// 查询单条数据
var row1 = await db.getOne(
table: 'user',
fields: '*',
where: {'id': 2},
);
print(row1);
// 查询多条数据
var row2 = await db.getAll(
table: 'user',
fields: '*',
where: {'id': ['>', 1]},
);
print(row2);
// 聚合函数操作
var count = await db.count(
table: 'user',
fields: '*',
);
print(count);
var avg = await db.avg(
table: 'user',
fields: 'id',
);
print(avg);
var min = await db.min(
table: 'user',
fields: 'id',
);
print(min);
var max = await db.max(
table: 'user',
fields: 'id',
);
print(max);
// 删除数据
var deleteCount = await db.delete(
table: 'user',
where: {'id': 3},
);
print(deleteCount);
// 更新数据
var updateCount = await db.update(
table: 'user',
updateData: {
'nickname': '更新测试-${rng.nextInt(100)}',
},
where: {'id': 4},
);
print(updateCount);
// 插入多条数据
var insertAllCount = await db.insertAll(
table: 'user',
insertData: [
{
'nickname': '批量插入测试-${rng.nextInt(100)}',
'telphone': '+113888888888',
'createTime': 1620577162252,
'updateTime': 1620577162252,
},
{
'nickname': '批量插入测试-${rng.nextInt(100)}',
'telphone': '+113888888888',
'createTime': 1620577162252,
'updateTime': 1620577162252,
}
],
);
print(insertAllCount);
// 关闭连接
await db.close();
}
希望以上内容能帮助你更好地理解和使用 mysql_utils
插件进行Flutter中的MySQL数据库操作。如果有任何问题或需要进一步的帮助,请随时提问!
更多关于Flutter数据库操作插件mysql_utils的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
更多关于Flutter数据库操作插件mysql_utils的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html
在Flutter中进行数据库操作时,通常会选择SQLite等嵌入式数据库,因为Flutter主要用于移动开发,而MySQL等服务器端数据库更适合在后端服务中使用。不过,如果你确实需要在Flutter应用中直接与MySQL数据库交互,这通常涉及到网络请求,而不是直接在Flutter应用中操作MySQL数据库。
mysql_utils
并不是一个广泛认知的Flutter插件,而且直接在客户端与MySQL交互通常不是最佳实践,因为这涉及到暴露数据库凭据和可能的安全风险。然而,如果你确实有一个特定的需求或场景,并且已经找到了一个名为 mysql_utils
的第三方库(注意:这不是Flutter官方或广泛使用的库),这里是一个如何使用它进行基本数据库操作的假设性示例。请注意,由于这个库不是标准的,下面的代码是基于假设的API设计。
首先,你需要在你的 pubspec.yaml
文件中添加依赖(假设这个库存在):
dependencies:
flutter:
sdk: flutter
mysql_utils: ^x.y.z # 替换为实际的版本号
然后运行 flutter pub get
来获取依赖。
接下来是一个假设性的使用示例,演示如何连接到MySQL数据库并执行查询:
import 'package:flutter/material.dart';
import 'package:mysql_utils/mysql_utils.dart'; // 假设的导入路径
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('MySQL Utils Demo'),
),
body: Center(
child: FutureBuilder<String>(
future: fetchData(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.done) {
if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Data: ${snapshot.data}');
}
} else {
return CircularProgressIndicator();
}
},
),
),
),
);
}
}
Future<String> fetchData() async {
// 假设的MySQL连接配置
final config = MySQLConfig(
host: 'your_mysql_host',
port: 3306,
user: 'your_mysql_user',
password: 'your_mysql_password',
database: 'your_database_name',
);
// 假设的MySQL连接和查询方法
final mysqlClient = MySQLClient(config);
try {
// 连接到数据库
await mysqlClient.connect();
// 执行查询
final result = await mysqlClient.query('SELECT * FROM your_table LIMIT 1');
// 处理结果(这里假设返回的是JSON字符串)
final rows = result.rows; // 假设的API,实际可能不同
if (rows.isNotEmpty) {
final firstRow = rows.first;
final firstColumnData = firstRow['your_column_name']; // 假设的API访问方式
return firstColumnData.toString();
} else {
return 'No data found';
}
} catch (e) {
// 处理错误
return 'Error: $e';
} finally {
// 确保连接被关闭
await mysqlClient.disconnect();
}
}
// 假设的MySQL配置类
class MySQLConfig {
final String host;
final int port;
final String user;
final String password;
final String database;
MySQLConfig({
required this.host,
required this.port,
required this.user,
required this.password,
required this.database,
});
}
// 假设的MySQL客户端类
class MySQLClient {
final MySQLConfig config;
late MySQLConnection connection; // 假设的连接对象
MySQLClient(this.config);
Future<void> connect() async {
// 假设的连接逻辑
connection = MySQLConnection(config.host, config.port, config.user, config.password, config.database);
await connection.open();
}
Future<MySQLResult> query(String sql) async {
// 假设的查询逻辑
return await connection.execute(sql);
}
Future<void> disconnect() async {
// 假设的断开连接逻辑
await connection.close();
}
}
// 假设的MySQL连接类和结果类
class MySQLConnection {
final String host;
final int port;
final String user;
final String password;
final String database;
MySQLConnection(this.host, this.port, this.user, this.password, this.database);
Future<void> open() async {
// 实际的连接逻辑(这里省略)
}
Future<MySQLResult> execute(String sql) async {
// 实际的查询执行逻辑(这里省略)
return MySQLResult([]); // 返回一个假设的结果对象
}
Future<void> close() async {
// 实际的断开连接逻辑(这里省略)
}
}
class MySQLResult {
final List<Map<String, dynamic>> rows;
MySQLResult(this.rows);
}
重要提示:
- 上面的代码是基于假设的API设计,因为
mysql_utils
并不是一个广泛认知的Flutter插件。实际的API可能会有所不同。 - 直接在Flutter应用中与MySQL数据库交互通常不是最佳实践。通常,你会在后端服务器上设置一个API,然后通过HTTP请求与后端交互。
- 如果确实需要在Flutter应用中与MySQL交互,请确保使用HTTPS来保护你的通信,并避免在客户端代码中硬编码数据库凭据。
如果你正在寻找一个实际的解决方案,考虑使用Flutter与后端服务(如Node.js、Django、Flask等)通信,后端服务再与MySQL数据库交互。这样可以更好地保护你的数据库凭据和数据安全。