反应本机和Mysql连接

时间:2019-10-31 07:32:04

标签: react-native

我正在使用React Native。我想在数据库中找到我在React Native中输入的数据。例如,在我输入的用户名的数据库中,“从表中选择ID('我在react native中输入的数据')”。我想找到带有用户名的表并提取用户的ID。

var name = this.state.username;

"select id from table where (name)"

我想像这样拉出用户名的ID。

2 个答案:

答案 0 :(得分:0)

您需要具有后端服务/ API才能从数据库中获取数据。尝试使用Node,并从其JavaScript编写一个简单的后端。您可以在后端执行sql查询,将数据从mySQL检索到节点服务器,然后可以使用fetch方法从后端服务器获取数据以进行本机响应。 (您的后端API和运行React本机应用程序的设备都应在同一网络上运行。)

答案 1 :(得分:0)

RN与Mysql之间没有直接连接。为此使用Node js。

步骤:1

npm install express

npm install body-parser

npm install mysql

步骤:2

const connection = mysql.createPool({
  host     : 'localhost', // Your connection adress (localhost).
  user     : 'root',     // Your database's username.
  password : '',        // Your database's password.
  database : 'my_db'   // Your database's name.
});

// Starting our app.
const app = express();

// Creating a GET route that returns data from the 'users' table.
app.get('/users', function (req, res) {
    // Connecting to the database.
    connection.getConnection(function (err, connection) {

    // Executing the MySQL query (select all data from the 'users' table).
    connection.query('SELECT * FROM users', function (error, results, fields) {
      // If some error occurs, we throw an error.
      if (error) throw error;

      // Getting the 'response' from the database and sending it to our route. This is were the data is.
      res.send(results)
    });
  });
});

// Starting our server.
app.listen(3000, () => {
 console.log('Go to http://localhost:3000/users so you can see the data.');
});

现在,我们如何在React Native App上获取这些数据?

很简单,我们使用提取功能。 为此,您不必直接使用“ localhost:3000”,而必须直接插入PC的IP地址。如果您使用“本地主机”,则需要访问智能手机/仿真器的本地主机。那不是我们想要的。请遵循以下示例:

test(){
    fetch('http://yourPCip:3000/users')
      .then(response => response.json())
      .then(users => console.warn(users))
  }