What is the recommended way to set up a Flutter mobile device to perform CRUD operations in a remote SQL Server instance?

huangapple go评论65阅读模式
英文:

What is the recommended way to set up a Flutter mobile device to perform CRUD operations in a remote SQL Server instance?

问题

我读过某处的信息说,尝试直接将Flutter连接到SQL Server是不明智的,因为Flutter的目的是能够与多个后端一起工作。如果这是真的,那么推荐的方式是什么?

有一种方法是构建一个后端,让Flutter可以与之通信,然后让后端指向SQL Server,但我不知道如何入手。

我已经尝试过的事情:

我已经尝试了一个名为sql_conn的Flutter包,它可以工作,但显然它使用的JDBC驱动程序已经有大约10年没有更新了。这让我担心,因为我将在生产环境中部署它。

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:sql_conn/sql_conn.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: "Test",
      home: TestPage(),
    );
  }
}

class TestPage extends StatefulWidget {
  const TestPage({Key? key}) : super(key: key);

  @override
  _TestPageState createState() => _TestPageState();
}

class _TestPageState extends State<TestPage> {
  Future<void> connect(BuildContext ctx) async {
    debugPrint("Connecting...");
    try {
      showDialog(
        context: context,
        builder: (context) {
          return const AlertDialog(
            title: Text("LOADING"),
            content: CircularProgressIndicator(),
          );
        },
      );
      await SqlConn.connect(
          ip: "192.168.128.176",
          port: "1433",
          databaseName: "MDCData",
          username: "AS",
          password: "112233");
      debugPrint("Connected!");
    } catch (e) {
      debugPrint(e.toString());
    } finally {
      Navigator.pop(context);
    }
  }

  Future<void> read(String query) async {
    var res = await SqlConn.readData(query);
    debugPrint(res.toString());
  }

  Future<void> write(String query) async {
    var res = await SqlConn.writeData(query);
    debugPrint(res.toString());
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('Plugin example app'),
        ),
        body: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            crossAxisAlignment: CrossAxisAlignment.center,
            children: [
              ElevatedButton(
                  onPressed: () => connect(context),
                  child: const Text("Connect")),
              ElevatedButton(
                  onPressed: () => read("SELECT * FROM IP_List"),
                  child: const Text("Read")),
              ElevatedButton(
                  onPressed: () =>
                      write("DELETE FROM IP_List WHERE LOC='vv1'"),
                  child: const Text("Write")),
              ElevatedButton(
                  onPressed: () =>
                      write("CREATE TABLE Persons (PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255),City varchar(255))"),
                  child: const Text("Create Table")),
              ElevatedButton(
                  onPressed: () => write("DROP TABLE Persons"),
                  child: const Text("Delete Table")),
              ElevatedButton(
                  onPressed: () => SqlConn.disconnect(),
                  child: const Text("Disconnect"))
            ],
          ),
        ));
  }
}
英文:

I read somewhere that trying to connect Flutter directly to SQL Server is unwise because the point of Flutter is to be able to work with multiple backends. If this is true, then what is the recommended way to do this?

One thing I've read about is to build a backend that Flutter can communicate with and then have the backend point to SQL Server, but I have no clue how to get started on this.

What I've done:

I've already tried this flutter package called sql_conn and it works, but apparently the JDBC driver it uses hasn't been updated in around 10 years. That worries me because I'm going to be deploying this in a production env.

import &#39;dart:async&#39;;
import &#39;package:flutter/material.dart&#39;;
import &#39;package:sql_conn/sql_conn.dart&#39;;
void main() {
WidgetsFlutterBinding.ensureInitialized();
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return const MaterialApp(
title: &quot;Test&quot;,
home: TestPage(),
);
}
}
class TestPage extends StatefulWidget {
const TestPage({Key? key}) : super(key: key);
@override
_TestPageState createState() =&gt; _TestPageState();
}
class _TestPageState extends State&lt;TestPage&gt; {
Future&lt;void&gt; connect(BuildContext ctx) async {
debugPrint(&quot;Connecting...&quot;);
try {
showDialog(
context: context,
builder: (context) {
return const AlertDialog(
title: Text(&quot;LOADING&quot;),
content: CircularProgressIndicator(),
);
},
);
await SqlConn.connect(
ip: &quot;192.168.128.176&quot;,
port: &quot;1433&quot;,
databaseName: &quot;MDCData&quot;,
username: &quot;AS&quot;,
password: &quot;112233&quot;);
debugPrint(&quot;Connected!&quot;);
} catch (e) {
debugPrint(e.toString());
} finally {
Navigator.pop(context);
}
}
Future&lt;void&gt; read(String query) async {
var res = await SqlConn.readData(query);
debugPrint(res.toString());
}
Future&lt;void&gt; write(String query) async {
var res = await SqlConn.writeData(query);
debugPrint(res.toString());
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(&#39;Plugin example app&#39;),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
ElevatedButton(
onPressed: () =&gt; connect(context),
child: const Text(&quot;Connect&quot;)),
ElevatedButton(
onPressed: () =&gt; read(&quot;SELECT * FROM IP_List&quot;),
child: const Text(&quot;Read&quot;)),
ElevatedButton(
onPressed: () =&gt; write(&quot;DELETE FROM IP_List WHERE LOC=&#39;vv1&#39;&quot;),
child: const Text(&quot;Write&quot;)),
ElevatedButton(
onPressed: () =&gt; write(
&quot;CREATE TABLE Persons (PersonID int, LastName varchar(255), FirstName varchar(255), Address varchar(255),City varchar(255))&quot;),
child: const Text(&quot;Create Table&quot;)),
ElevatedButton(
onPressed: () =&gt; write(
&quot;DROP TABLE Persons&quot;),
child: const Text(&quot;Delete Table&quot;)),
ElevatedButton(
onPressed: () =&gt; SqlConn.disconnect(),
child: const Text(&quot;Disconnect&quot;))
],
),
));
}
}

答案1

得分: 2

通常情况下,直接让任何类型的应用程序连接数据库都是不良实践。而Flutter选择保持数据库不可知性的原因,并不是说你不能直接连接SQL Server,而是说你不必只使用SQL Server。

但首选的做法是在项目范围内使用Flutter -> API -> SQL Server。API层会处理Flutter的请求,并管理与SQL Server的数据传输。至于最佳选择,完全取决于您,因为您将不得不在某处托管API,如果您有一个网站,您可以让它在同一主机上“运行”,使用子域名或端口号区别。但关于要在哪种语言或框架中构建API,有很多选择,例如NodeJS Express、Deno、Flask、ASP .NET等。

英文:

Typically it is bad practice to have any type of application connect directly to a database. And the reasoning for flutter to be database agnostic, is not why you shouldn't connect directly to SQL Server, it is just saying you don't have to only use SQL Server.

But the preferred practice is on project scope level you have flutter -> API -> SQL Server. The API layer is what would handle the flutter requests and manage getting/sending data to SQL Server. As for the best option that is completely up to you, since you will have to host the API somewhere, if you have a website you can have it "live" on the same host, with a subdomain or port number difference. But as for what to build the api in there are plenty of options, NodeJS Express, Deno, Flask, ASP .NET, etc.

huangapple
  • 本文由 发表于 2023年6月13日 00:03:41
  • 转载请务必保留本文链接:https://go.coder-hub.com/76458417.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定