如何将Flutter连接到localhost MySQL数据库 [英] How to connect flutter to localhost mysql database

查看:1357
本文介绍了如何将Flutter连接到localhost MySQL数据库的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将localhost mysql db连接起来但无法执行.我用以下连接尝试了mysql1:

I want to connect a localhost mysql db to flutter but I'm failing to do so. I tried mysql1 with these connections:

ConnectionSettings(
        host: '10.0.2.2',
        port: 3306,
        user: 'root',
        password: "root",
        db: 'company'

,我尝试用'localhost'替换主机,但没有用.有什么帮助吗?我没有使用模拟器.

and i tried replacing host by 'localhost' and it didn't work. Any help? I am not using an emulator.

推荐答案

直接连接到MySQL(或直接从客户端进行任何其他数据库访问)的连接不是一个好主意,除了Firebase. 如果要与MySql db交互,更好的解决方案是创建服务器应用程序并公开一些HTTP REST API(使用node.js,php等).使用API​​,您还可以为客户端提供令牌,以访问您的数据. 您可以发出HTTP请求 https://api.dartlang .org/stable/1.24.3/dart-io/HttpClient-class.html .

A connection directly to MySQL (or any other database access directly from clients) is not a good idea, except Firebase. If you want to interact with the MySql db a better solution is to create a server app and expose some HTTP REST API (with node.js, php ect.). With the API you can provide also a token for the client in order to access your data. You can make HTTP requests https://api.dartlang.org/stable/1.24.3/dart-io/HttpClient-class.html.

现在,如果出于任何原因仍要直接连接到MySQL,请记住,在这种情况下,任何客户端应用程序都可以使用 write 权限访问您的数据库(这不是一个好习惯,全部!)仅作为一个测试示例,您可以尝试创建一个php文件:

Now if for any reason you want still to connect directly to MySQL just keep in mind that any client application can access your DB with write permission in this case (and this is not a good practice at all!) just for a test example you can try creating a php file:

//连接并插入数据示例

// Connect and insert data example

<?php 
    if (isset($_POST["value"])) {
        $servername = "localhost";
        $user = "username";
        $pw = "password";
        $db = "data";
        #Connect to Server
        $con = new Mysqli($servername, $user, $pw, $db) or die(Mysqli_errno());

        $value =htmlspecialchars(stripslashes(trim($_POST["value"])));

        $sql = $con->prepare("INSERT INTO tableName (value) VALUES ('$value')");
        $result = $sql->execute();
        if ($result) {
            echo "Success";
        }
        else {
            echo "Failed";
        }
        $con->close();
    } 
    else {
       echo "Not found";
    } 
?>

还需要在http.post上写出发出请求的颤动部分

Also need to write the flutter part that make the request on http.post

void post() async {
    var result = await http.post(
        "http://{your url}/index.php",
         body: {
           "value": "Test DB Connection"
         }
    );
    print(result.body);
}

这篇关于如何将Flutter连接到localhost MySQL数据库的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆