Flutter MySQL数据库连接插件pip_services3_mysql的使用
Flutter MySQL数据库连接插件pip_services3_mysql的使用
该模块是Pip.Services多语言微服务工具包的一部分。
该模块包含以下包:
- Build - 构造组件的标准工厂
- Connect - 配置数据库连接的工具
- Persistence - 用于与数据库交互的抽象类,可以用于连接集合并执行基本的CRUD操作
快速链接:
使用
在项目的pubspec.yaml
文件中添加以下依赖项:
dependencies:
pip_services3_mysql: ^1.0.0 # 替换为最新版本号
然后从命令行安装包:
pub get
开发
开发时需要安装以下前置条件:
- Dart SDK 2
- Visual Studio Code 或其他IDE
- Docker
安装依赖项:
pub get
运行自动化测试:
pub run test
生成API文档:
./docgen.ps1
提交更改前,运行docker化构建和测试:
./build.ps1
./test.ps1
./clear.ps1
联系方式
该模块由以下人员创建和维护:
- Sergey Seroukhov
- Danil Prisiazhnyi
完整示例代码
以下是一个完整的示例,展示如何使用pip_services3_mysql
插件连接到MySQL数据库并执行基本的CRUD操作。
1. 初始化项目
首先确保已安装Dart SDK,并初始化一个新的Flutter项目:
flutter create mysql_example
cd mysql_example
在pubspec.yaml
中添加pip_services3_mysql
依赖:
dependencies:
pip_services3_mysql: ^1.0.0 # 替换为最新版本号
安装依赖:
flutter pub get
2. 编写MySQL连接代码
在lib/main.dart
中编写以下代码:
import 'package:pip_services3_commons/pip_services3_commons.dart';
import 'package:pip_services3_components/pip_services3_components.dart';
import 'package:pip_services3_mysql/pip_services3_mysql.dart';
void main() {
// 配置MySQL连接参数
var config = ConfigParams.fromTuples([
"connection.host", "localhost",
"connection.port", 3306,
"connection.database", "test_db",
"credential.username", "root",
"credential.password", "password"
]);
// 创建MySQL连接器
var mysqlPersistence = MysqlPersistence();
mysqlPersistence.configure(config);
// 启动连接
mysqlPersistence.open("12345").then((_) {
print("MySQL connection established");
// 执行插入操作
var item = Map<String, dynamic>();
item["id"] = "1";
item["name"] = "Test Item";
mysqlPersistence.create(null, "items", item).then((result) {
print("Inserted item: $result");
// 查询数据
mysqlPersistence.getOneByFilter("items", FilterParams.fromTuples(["id", "1"]))
.then((itemResult) {
print("Fetched item: $itemResult");
// 更新数据
itemResult["name"] = "Updated Test Item";
mysqlPersistence.update(null, "items", itemResult).then((updatedItem) {
print("Updated item: $updatedItem");
// 删除数据
mysqlPersistence.deleteById(null, "items", "1").then((_) {
print("Deleted item");
mysqlPersistence.close("12345");
});
});
});
});
}).catchError((err) {
print("Error: $err");
});
}
3. 运行示例
确保本地MySQL服务器正在运行,并且数据库test_db
已创建。然后运行应用程序:
flutter run
4. 输出结果
成功运行后,控制台将输出类似以下信息:
MySQL connection established
Inserted item: {id: 1, name: Test Item}
Fetched item: {id: 1, name: Test Item}
Updated item: {id: 1, name: Updated Test Item}
Deleted item
更多关于Flutter MySQL数据库连接插件pip_services3_mysql的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html
1 回复