鸿蒙App连接远程SQL数据库框架与核心代码
OpenHarmony应用采用分层架构设计,包含UI层、业务逻辑层、数据访问层和网络层。UI层使用ArkTS编写,业务逻辑层处理数据转换和交互逻辑,数据访问层封装SQL操作,网络层负责WiFi通信与远程数据库连接。在中声明网络权限和WiFi权限:实现WiFi状态检测与数据库连接管理:定义与数据库字段对应的数据模型:使用ArkUI实现数据展示页面:远程服务器需提供API接口处理SQL请求:该框架完整
·
应用框架设计
OpenHarmony应用采用分层架构设计,包含UI层、业务逻辑层、数据访问层和网络层。UI层使用ArkTS编写,业务逻辑层处理数据转换和交互逻辑,数据访问层封装SQL操作,网络层负责WiFi通信与远程数据库连接。
权限配置
在config.json中声明网络权限和WiFi权限:
{
"module": {
"reqPermissions": [
{
"name": "ohos.permission.INTERNET"
},
{
"name": "ohos.permission.GET_WIFI_INFO"
}
]
}
}
网络连接模块
实现WiFi状态检测与数据库连接管理:
import wifi from '@ohos.wifi';
import http from '@ohos.net.http';
class NetworkManager {
private static instance: NetworkManager;
private httpRequest: http.HttpRequest;
private constructor() {
this.httpRequest = http.createHttp();
}
public static getInstance(): NetworkManager {
if (!NetworkManager.instance) {
NetworkManager.instance = new NetworkManager();
}
return NetworkManager.instance;
}
async checkWifiConnected(): Promise<boolean> {
const info = await wifi.getLinkedInfo();
return info.ssid !== null;
}
async queryDatabase(sql: string): Promise<string> {
const url = "http://your-database-server.com/api/query";
return new Promise((resolve, reject) => {
this.httpRequest.request(
url,
{
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: { sql: sql }
},
(err, data) => {
if (err) {
reject(err);
} else {
resolve(data.result);
}
}
);
});
}
}
数据模型定义
定义与数据库字段对应的数据模型:
class User {
userId: number;
userName: string;
userAge: number;
constructor(data: any) {
this.userId = data.id || 0;
this.userName = data.name || '';
this.userAge = data.age || 0;
}
}
UI界面实现
使用ArkUI实现数据展示页面:
@Entry
@Component
struct QueryPage {
@State users: User[] = [];
@State sql: string = 'SELECT * FROM users WHERE age > 20';
async queryData() {
try {
const netMgr = NetworkManager.getInstance();
const isConnected = await netMgr.checkWifiConnected();
if (!isConnected) {
prompt.showToast({ message: '请连接WiFi' });
return;
}
const result = await netMgr.queryDatabase(this.sql);
this.users = JSON.parse(result).map((item: any) => new User(item));
} catch (error) {
prompt.showToast({ message: `查询失败: ${error.message}` });
}
}
build() {
Column() {
TextInput({ text: this.sql })
.onChange((value: string) => {
this.sql = value;
})
Button('执行查询')
.onClick(() => this.queryData())
List({ space: 10 }) {
ForEach(this.users, (user: User) => {
ListItem() {
Column() {
Text(`ID: ${user.userId}`)
Text(`姓名: ${user.userName}`)
Text(`年龄: ${user.userAge}`)
}
}
})
}
}
}
}
服务端接口示例(PHP)
远程服务器需提供API接口处理SQL请求:
<?php
header("Content-Type: application/json");
$db = new PDO('mysql:host=localhost;dbname=test', 'username', 'password');
$data = json_decode(file_get_contents('php://input'), true);
$sql = $data['sql'];
try {
$stmt = $db->query($sql);
$result = $stmt->fetchAll(PDO::FETCH_ASSOC);
echo json_encode($result);
} catch (PDOException $e) {
http_response_code(500);
echo json_encode(['error' => $e->getMessage()]);
}
?>
安全增强措施
- 使用HTTPS加密通信
- 实现SQL注入防护:
function validateSql(sql: string): boolean {
const forbidden = ['DROP', 'DELETE', 'UPDATE', 'INSERT'];
return !forbidden.some(cmd => sql.toUpperCase().includes(cmd));
}
- 添加请求超时处理:
this.httpRequest.request(
url,
{
method: http.RequestMethod.POST,
header: { 'Content-Type': 'application/json' },
extraData: { sql: sql },
connectTimeout: 10000,
readTimeout: 10000
},
// ...回调处理
);
性能优化建议
- 实现本地缓存机制
- 使用分页查询减少数据传输量
- 添加加载状态指示器
- 实现自动重连机制
该框架完整实现了从WiFi检测到远程数据库查询的全流程,核心代码约200行,实际开发中可根据具体业务需求扩展更多功能模块。
更多推荐
所有评论(0)